Settimeout Happens Only Once In A Loop Expression
This is an example: function func1() { setTimeout(function(){doSomething();}, 3000); } for(i=0;i<10;i++) { func1(); } after executing it , the delay happens only in the
Solution 1:
You are scheduling 10 calls, but the problem is all are getting scheduled for the same time, ie after 3 seconds.
If you want to call them incrementally then you need to increase the delay in each call.
A solution will be is to pass a delay unit value to the func1
like
functionfunc1(i) {
setTimeout(function() {
doSomething();
}, i * 500);//reduced delay for testing
}
for (i = 0; i < 10; i++) {
func1(i + 1);
}
var counter = 0;
functiondoSomething() {
snippet.log('called: ' + ++counter)
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --><!-- To show result in the dom instead of console, only to be used in the snippet not in production --><scriptsrc="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Solution 2:
The loop will schedule 10 timeouts all to be completed after 3 seconds. You can use recursion with setTimeout
:
function loopAsync(delay, n, f) {
setTimeout(function() {
if (n > 0) {
f()
loopAsync(delay, n - 1, f)
}
}, delay)
}
loopAsync(3000, 10, doSomething)
Solution 3:
What is heppening is that you are calling 10 times (without delay) func1()
then what you have is 10 functions all on the same time, the solution is simple, use setInterval, here is a fiddle
Solution 4:
With async.js:
async.timesSeries(5, function (n, next) {
setTimeout(function(){
doSomething();
next();
}, 3000);
});
Solution 5:
If you want iterate with constant delay, IMHO you better use setInterval:
var loops = 9,
intervalId = setInterval(function () {
// My super code goes hereconsole.log(loops);
loops-- <= 0 && (clearInterval(intervalId));
}, 3000);
I've made a jsfiddle for you.
Post a Comment for "Settimeout Happens Only Once In A Loop Expression"