开发者

Execute function every nth second

开发者 https://www.devze.com 2022-12-24 05:53 出处:网络
I\'ve made this snippet that clicks a link after 10th second: function timeout() { window.setTimeout(function() {

I've made this snippet that clicks a link after 10th second:

function timeout() {
    window.setTimeout(function() {
     $('img.left').click();
    }, 1000);
    setTimeout("timeout()", 1000); 
}
timeout();

My question is, how do I execute this function every 10th second, instead of just once?

Is this the best way to do this, or is there some kind of nifty jQuery开发者_JS百科 method that you prefer?


Use setInterval instead of setTimeout

http://javascript.about.com/library/blstvsi.htm


setInterval(yourFunction, 1000 * 10);

(time in miliseconds: 1000 is 1 second, 1000 * 10 is 10 seconds)

Which works better than "setTimeout"; more readable, etc.


I use this approach for polling, recurring updates, and animations:

var timerId = setInterval(function() {

    if (timeToStopConditionMet) {
        clearInterval(timerId);
        return;
    }

    // your recurring code

}, 10000); // 10000 makes this code execute every 10 seconds


Yes, setInterval(timeout, 1000) does nearly the same thing. It's somewhat different in that the the next interval starts counting immediately after 1000ms, not after the script that runs has completed (or even started). I advocate against it for precisely this reason, for most purposes. Your implementation is better, IMO.

Also, you don't need to pass the timeout function in a string, you can just pass the reference directly, i.e. setTimeout(timeout, 1000) instead of setTimeout("timeout()", 1000).


window.onload=function(){
    GetCount(dateFuture1, 'countbox1');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消