HTML and CSS Reference
In-Depth Information
// Increase the value of current by one
update(current + 1);
// Execute every 500 ms.
}, 500);
}
}
Listing 8-2 uses setInterval .
Listing 8-2. Using setInterval
// Define the amount of times the loop is going to get called,
// initialise the counter and define an empty variable for our timer.
var maxCount = 3,
current = 0, //
intervalId = null;
function update() {
// Execute the function 3 times
if (current < maxCount) {
// Do Something
// Increase the value of the counter by one
current += 1;
} else {
// If the function has been called 3 times, stop the timer.
clearInterval(intervalId);
}
}
// Define the interval and save the timerId to a variable. Call every 500 ms.
intervalId = setInterval(update, 500);
The second parameter of both functions is the delay. Common reason would dictate that if you want to make the
loop run as many times as possible per second, you could set it to zero. Unfortunately, that'd produce a similar result
to doing an infinite while loop. For this reason, the delay (referred to as DOM_MIN_TIMEOUT_VALUE in the spec) used to
be clamped to a minimum value of 10 ms.
However, both methods suffered (and still do) from a very serious problem: if the window or tab is inactive, or
(in the case of a mobile application) if you switch to another application, both functions will continue to be called at
10 ms, consuming valuable processing and battery power.
In modern browsers, both setTimeout and setInterval have a DOM_MIN_TIMEOUT_VALUE of 4 ms. They also
include a new function that not only behaves similarly to setTimeout and setInterval , but that also solves the
“inactive window” problem. This function is defined in the document “Timing control for script-based animations”
( http://www.w3.org/TR/animation-timing/ ) and it's called requestAnimationFrame .
 
Search WWH ::




Custom Search