javascript interactive

JavaScript Interactive — a console crash course

3.9 Delayed Execution

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.

JavaScript does not support threading with shared memory. As an alternative, the browsers allow the usage of timer events to delay execution. This means that all code is executed in the same browser event handler thread that also handles HTML changes and similar.

function worker() { print('working...'); }

setTimeout(worker, 500);

The browser built-in setTimeout() function calls a function after a specified millisecond delay has passed. In this case a simple logging function is used, but any zero-argument function is ok.
function repeater() { print('repeating...'); }

var handle = setInterval(repeater, 1000)

The built-in setInterval() function can be used to call a function repeatedly...
function stopRepeater() {

setTimeout(stopRepeater, 3100);

...until stopped with clearInterval(). A similar clearTimeout() function is available to cancel setTimeout() calls.

The handle value returned by setTimeout() and setInterval() is required to cancel the calls. It is a good idea to store this value.
setTimeout(function () { print('immediate'); }, 0)

The setTimeout() function is sometimes called with a zero delay. This results in the function being executed as soon as possible (but not immediately). It is commonly used in event handlers to allow the current browser event to finish propagation before performing some action.

Index 1 2 3 4 5 6 7 8 9