views:

109

answers:

4

Total JavaScript n00b question right here:

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 method that you prefer?

+1  A: 

setInterval(yourFunction, 1000 * 10);

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

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

Pindatjuh
+3  A: 

Use setInterval instead of setTimeout

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

Phil
Note that the pivotal difference between the two is this: `setInterval()` runs every X milliseconds, a series of self-calling `setTimeout()` functions take the actual execution time of the payload function into account. Sometimes the latter is more desirable.
Tomalak
Furthermore, if there is something interrupting (like events triggering) the browser, the intervals can queue up and fire many times in a row. That's why I prefer setTimeout. More info: http://ejohn.org/blog/how-javascript-timers-work/
Kimmo Puputti
+1  A: 

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
Is this acceptable for doing periodic refreshes via AJAX without tying up CPU resources?
Paul Nathan
I don't have any empirical data, but in my experience, as long as the function is reasonably short and efficient and the interval between calls is large enough, the CPU consumption is non-consequential.In terms of periodic refreshes, this method should be fine, but don't forget if you are doing DOM manipulations on elements with attached events, those events are not disposed when the elements they are attached to are removed from the DOM.
+1  A: 

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).

bcherry