Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code every 10 seconds but start on 0 seconds too

I want to execute code every 10 seconds, but also on page load. I mean I want the code to execute when the page loads initially then every 10 seconds. The following code only executes the code initially after 10 seconds.

window.setInterval(function(){
  /// call your function here
}, 10000);

Thanks!

like image 558
user1937021 Avatar asked Mar 21 '13 13:03

user1937021


3 Answers

You can do this :

(function(){
   var f = function() {
     // do something
   };
   window.setInterval(f, 10000);
   f();
})();

The IIFE is used here to avoid polluting the enclosing namespace.

like image 169
Denys Séguret Avatar answered Sep 18 '22 22:09

Denys Séguret


First execute the function in $.ready and then start the interval with that same function.

Something along the lines of:

$(function() {
    var f = function() { };

    f();
    window.setInterval(f, 10000);
});
like image 36
Andreas Grech Avatar answered Sep 19 '22 22:09

Andreas Grech


Don't inline the function, and then just call it immediately:

window.setInterval(foo, 10000);
foo();

function foo()
{
    //Do Stuff
}
like image 31
PhonicUK Avatar answered Sep 18 '22 22:09

PhonicUK