alias51
alias51

Reputation: 8648

How to start a script on page load and then use setInterval

I have a function, timer() that I want to run once immediately on page load, and then to run every second thereafter.

At present I have the following code using setInterval:

$(document).ready(function() {
 var timer = function(){
    ...
}

timer();

setInterval(function(){
      timer();
}, 1000);
});

Note, I don't just want to use setInterval alone, as this creates a 1sec delay after the page loads

However, my use of timer(); seems to stop other script on the page working. Any ideas? No errors in the console.

Upvotes: 0

Views: 2078

Answers (2)

Teemu
Teemu

Reputation: 23416

I'd use setTimeout() instead:

$(document).ready(function() {
    var timerLoop;
    var timer = function(){
                ...
            timerLoop = setTimeout(timer, 1000);
        };
    timer();
}

Notice the timerLoop variable, which you can use to stop the "interval" (clearTimeout(timerLoop);) if needed.

Timeouts are not really asynchronous, they are just timed. If there's another script running, a timed script is executed after the previous script has been finished.

I'd prefer setTimeout() instead of seInterval(), since the latter has a disadvantage: If there's another script blocking the execution of timed calls set by setInterval(), these calls are stacked, and when the blocking script is finished, all stacked calls are executed as fast as possible. Usually this is undesired behaviour.

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Try console.log(timer) and you will clearly see that it is a number, not a function you can call.

Instead, you have to manually call the function as well as set the timer.

function timer() {
    // do something
}
$(function() {
    timer();
    setInterval(timer,1000);
});

Alternatively, you can use repeated timeouts:

function timer() {
    // do something
    setTimeout(timer,1000);
}
$(timer);

Upvotes: 0

Related Questions