Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript while loop or set interval with dynamic delay

Tags:

javascript

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>
like image 987
sugunan Avatar asked Dec 04 '25 10:12

sugunan


1 Answers

Use setTimeout instead and keep recursive call.

function someLoop() {
    var nextExecutionTime = calc();
    setTimeout(someLoop, nextExecutionTime);
}
like image 82
Joey Chong Avatar answered Dec 06 '25 23:12

Joey Chong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!