2

I need to have a never ending loop in javascript. This will be almost like set interval. But for each loop the time delay need to be applied dynamically. The delay value will be changing on each loop. So is it possible to use while with some kind of sleep function? Or is it possible to change the set interval time for each iteration?

following code didn't give the delay. Always take the first value given to it.

<script>
var someTimeoutVar = 1000;
var inc = 1;
setInterval(function() { 
    inc++;
    someTimeoutVar = inc * 1000;
    console.log(someTimeoutVar);
}, someTimeoutVar)
</script>
sugunan
  • 4,408
  • 6
  • 41
  • 66

3 Answers3

7

Use setTimeout instead and keep recursive call.

function someLoop() {
    var nextExecutionTime = calc();
    setTimeout(someLoop, nextExecutionTime);
}
Joey Chong
  • 1,470
  • 15
  • 20
0

You can use:

setInterval(expression, someTimeoutVar);

and then change your someTimeoutVar as you need to

Alex J
  • 1,029
  • 6
  • 8
  • I tried your method it didn't work. `` – sugunan Dec 19 '14 at 04:22
0
function repeatedOperation() {
  /* Do operations here. */
  /* ... */
  /* You can return something if desired to help
   * the other function decide what the new timeout
   * delay should be. By default, I have set the new
   * timeout delay to be whatever is returned here
   * plus a random fuzz time between 0-1 second. */
  return 1; /* interpreted as milliseconds */
}

function updateTimeout(result) {
  /* Compute new timeout value here based on the
   * result returned by the operation.
   * You can use whatever calculation here that you want.
   * I don't know how you want to decide upon a new
   * timeout value, so I am just giving a random
   * example that calculates a new time out value
   * based on the return value of the repeated operation
   * plus an additional random number. */
  return Math.round(result + 1000*Math.random());
  /* This might have been NaN. We'll deal with that later. */
}

function proxyInterval(oper, delay) {
  var timeout = delay(oper());
  setTimeout(function() { proxyInterval(oper, delay); }, timeout-0 || 1000);
  /* Note: timeout-0 || 1000 is just in case a non-numeric
   * timeout was returned by the operation. We also
   * could use a "try" statement, but that would make
   * debugging a bad repeated operation more difficult. */
}

/* This is how to use the above code: */

proxyInterval(repeatedOperation, updateTimeout);
Joseph Myers
  • 6,434
  • 27
  • 36
  • OP didn't say anything about using a random value. – JLRishe Dec 19 '14 at 04:30
  • Exactly. The line of code in the `updateTimeout` function is meant to be arbitrary, whatever calculation is wanted. That's just an example of a calculation, and it allows for the calculation to also depend on the value returned by the repeated operation function. – Joseph Myers Dec 19 '14 at 04:31