Execute a function every n-th second

I made this snippet that clicks the link after the 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 10 seconds, and not just once?

Is this the best way to do this, or is there some great jQuery method you prefer?

+3
source share
5 answers

Use setIntervalinsteadsetTimeout

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

+7
source

setInterval(yourFunction, 1000 * 10);

(time in milliseconds: 1000 - 1 second, 1000 * 10 - 10 seconds)

What works better than "setTimeout"; more readable etc.

+3
source

, :

var timerId = setInterval(function() {

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

    // your recurring code

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

Yes, setInterval(timeout, 1000)it does almost the same thing. This is somewhat different in that the next interval starts counting right after 1000 ms, and not after the script that runs (or even starts) is executed. I am opposed to this precisely for this reason, for most purposes. Your implementation is better, IMO.

In addition, you do not need to pass the function timeoutto a string, you can just pass the link directly, i.e. setTimeout(timeout, 1000)instead of setTimeout("timeout()", 1000).

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

Source: https://habr.com/ru/post/1738417/


All Articles