Reputation: 101
In my implementation ,method is executed every 5 sec. But I want to increment the time interval in series . First run at 5th sec , second run at 15th sec , third run at 30th sec . the below code is still executing every 5 sec . Can someone help to resolve the issue
var timer = 5000;
var win = setInterval( callback,timer);
function callback () {
timesRun += 1;
if (totalResultUpdated > totalResultInitial)
{
clearInterval(win);
timer*=2;
fun(false);
}
win=setInterval(callback,timer);
}
Upvotes: 1
Views: 1867
Reputation: 3718
You can simply use a recursion for this :
function setIncrementalInterval(fn, initTime, incr){
setTimeout(fn,initTime)
setTimeout(function(){setIncrementalInterval(fn, initTime+incr, incr)},initTime)
}
let time = Date.now()
function myFunction(){
console.log(Date.now()-time)
}
setIncrementalInterval(myFunction,1000,1000)
here initial delay is 1000ms and increments by 1000ms
Upvotes: 0
Reputation: 22875
let timeout = 5000;
let intervalId = setInterval(callback, timeout);
function callback () {
console.log('Do something here', new Date());
clearInterval(intervalId);
timeout *= 2;
intervalId = setInterval(callback, timeout);
}
Upvotes: 1
Reputation: 138257
You cannot just set timer
to another value. Once an interval is started, it will continue with the time it was set to initially. Instead of starting an interval i would recommend to use a pseudorecursive timeout instead:
function increasingInterval(fn, time) {
function next(i) {
fn();
setTimeout(next, time * i, i + 1);
}
setTimeout(next, time, 2);
}
So you can do:
increasingInterval(function() {
console.log("something");
}, 5000);
Upvotes: 3