Isaac Lubow
Isaac Lubow

Reputation: 3573

How does Javascript timing really work?

Say I have some code:

setInterval(foo,1000); // here is an interval that causes a function to repeat
function foo(){
//a number of lines of code
}

Now, i think of this as causing foo() to be executed every second by the system clock, whereas this:

function foo(){
//a number of lines of code
setTimeout(foo,1000);    } //here is a timeout that causes the function to repeat

Am I correct in guessing that the latter function would be executed less often in a given period of time, because I'm inserting a pause between executions (which, themselves, take a measurable amount of time)? Any further points or enlightenment on this mechanism would be welcomed.

Upvotes: 0

Views: 123

Answers (3)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 828170

Let me quote an article about timers by John Resig, which specifically addresses your question:

setTimeout(function(){
  /* Some long block of code... */
  setTimeout(arguments.callee, 10);
}, 10);

setInterval(function(){
  /* Some long block of code... */
}, 10);

These two pieces of code may appear to be functionally equivalent, at first glance, but they are not. Notably the setTimeout code will always have at least a 10ms delay after the previous callback execution (it may end up being more, but never less) whereas the setInterval will attempt to execute a callback every 10ms regardless of when the last callback was executed.

Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified delay).

Keep also in mind that accuracy of JavaScript timers differs between browsers and platforms.

Upvotes: 2

Nagarajan Ganesh
Nagarajan Ganesh

Reputation: 573

"function foo(){

//a number of lines of code

setTimeout(foo,1000);

}"

Here in your code, there is no end to your foo(), actually it creates indefinite looping. Better remove your "setTimeout()" function and then you can try to place it somewhere other than within foo().

Upvotes: -1

casablanca
casablanca

Reputation: 70721

Now, i think of this as causing foo() to be executed every second by the system clock

There are no hard guarantees. The interval will be at least one second, but it can be more depending on CPU load as well as the resolution of the OS timer.

Am I correct in guessing that the latter function would be executed less often in a given period of time, because I'm inserting a pause between executions

It will be the same or less, depending on whether foo() takes a significant amount of time to execute.

Upvotes: 0

Related Questions