OneCompiler

Javascript: retry function

144

This code will try the given 'code' for 'times' times until it is success or reach the limit of loop. This would help when you try to access a unstable server that sometimes work sometimes won't, and you want to access it a multiple times before sending out an error.

function retry(code,times,condition,errorMessage) {
  try {
    for (var i = 0; (i < times && eval(condition)) || i === 0; i++) {
      eval(code);
      if (i === times-1 && eval(condition) && typeof errorMessage !== "undefined") {throw new Error(errorMessage)};
    }
  } catch (e) {
    console.log("Error Message: '" + e + "'");
  }
}

An simulation:

function retry(code,times,condition,errorMessage) {
  try {
    for (var i = 0; (i < times && eval(condition)) || i === 0; i++) {
      eval(code);
      if (eval(condition)) {console.log("ERROR!! #" + i)} else {console.log("Success!! #" + i)};
      if (i === times-1 && eval(condition) && typeof errorMessage !== "undefined") {throw new Error(errorMessage)};
    }
  } catch (e) {
    console.log("Error Message: '" + e + "'");
  }
}

retry("var response = (i === 5) ? 'Oh, I got a response!' : undefined;",10,"typeof response === 'undefined'")
retry("var response = (i === -1) ? 'Oh, I got a response!' : undefined;",10,"typeof response === 'undefined'")