Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
-4
rated 0 times [  2] [ 6]  / answers: 1 / hits: 89128  / 12 Years ago, sat, may 12, 2012, 12:00:00

In a simple setInterval



setInterval(function() {
// Do something every 9 seconds
}, 9000);


The first action will happen after 9 seconds (t=9s). How to force the loop to perform the first action immediately (t=0)?



I think it is due to the mechanism of setInterval to have Delay - Action - Delay - Action ... loop; instead of Action - Delay - Action - Delay ... loop.



EDIT: My function is indeed a loop as



setInterval(function(){
$('.test').each(function(idx){
var duration = 1000;
$(this).delay(duration*idx);
Some stuff here
});
}, 4000);

More From » jquery

 Answers
6

Keep it simple. You can use a named function instead of an anonymous function; call it and set an interval for it.



function doSomething() {
console.log(tick);
}
doSomething();
setInterval(doSomething, 9000);


Create a scope if necessary:



(function() {
function doSomething() {
console.log(tick);
}
doSomething();
setInterval(doSomething, 9000);
})();


Finally, the following works without creating or affecting x:



setInterval(function x() {
console.log(tick);
return x;
}(), 9000);

[#85629] Friday, May 11, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anyssaarielles

Total Points: 415
Total Questions: 107
Total Answers: 92

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
;