Press F5 to view again.
ID of the interval:
Counter:
The function window.setInterval(function, delay)
executes the called function all delay milliseconds. This may be used for animations (like in the example above), but also for checking whether the page is already loaded completely — by putting an element at the end of the page and checking whether it exists.
window.setInterval
returns the ID of the running process. The process can be stopped with clearInterval(processID)
.
Code for the box above:
var B = 253;
var INTERVAL_ID
var COUNTER_INTERVAL = 0;
var DIFF = -1;
function intervalStart() {
INTERVAL_ID = window.setInterval(intervalRun, 10);
insertText('intervalID', INTERVAL_ID, false);
}
function intervalRun() {
document.getElementById('bg').style.backgroundColor = 'rgb(' + B + ', ' + B + ', 255)';
B += DIFF;
if (B >= 255 || B <= 130) DIFF = -DIFF;
COUNTER_INTERVAL += 1;
insertText('counterInterval', COUNTER_INTERVAL + ' -- ' + B, false);
if (COUNTER_INTERVAL >= 250) {
clearInterval(INTERVAL_ID);
}
}
window.onload = intervalStart;
]]>
window.setInterval
and window.setTimeout
can also execute JavaScript code as a string object instead of a function object. This should not be used due to security and other reasons.