Reputation: 1732
Using setInterval/ setTimeout, how can I make sure my function FINISH executing before waiting for some time and then executing again, FINISH, then wait, and so on. Thanks.
Upvotes: 0
Views: 435
Reputation: 3808
function execute_and_wait( repeated_function, time_delay ) {
var next_run = function () {
var complete_callback = function () {
next_run();
}
var killcode = setTimeout(
function () {
repeated_function(complete_callback);
},
time_delay
);
return killcode;
};
return next_run;
}
Usage :
// Runs a function that prints hi every 2 seconds
// Kills it after 10 seconds
var ka = function (r) { alert('hi'); r(); };
var runka = execute_and_wait(ka,2000);
var killka = runka();
setTimeout(
function () {
clearTimeout(killka);
},
10000
);
Upvotes: 0
Reputation: 1075309
That's the classic use case for a chained series of setTimeout
:
setTimeout(foo, yourInterval);
function foo() {
// ...do the work...
// Schedule the next call
setTimeout(foo, yourInterval);
}
Since setTimeout
only schedules a single call to the function, you reschedule it (if appropriate) after the function has done its work.
Unlike setInterval
, this works correctly even if the work your function does is asynchronous, as long as you reschedule it from the callback of the asynchronous work. For example:
setTimeout(foo, yourInterval);
function foo() {
callSomethingAsynchronous(function() {
// ...we're in the async callback, do the work...
// ...and now schedule the next call
setTimeout(foo, yourInterval);
});
}
In contrast, if you're doing something asynchronous, using setInterval
rapidly becomes chaotic.
Upvotes: 5