Console Learner — An interactive JavaScript course.


3.9 Delayed Execution

JavaScript does not support threading with shared memory. As an alternative, browsers support delayed execution via timer events. This means that all code is executed in sequence in the same browser thread that handles HTML events, etc.

Timer events do not guarantee an exact execution time, since other JavaScript code cannot be interrupted to run the timer.

For the same reason, large jobs should be split up to avoid blocking normal browser event handling.
>>>
setTimeout(() => print('working...'), 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.
>>>
var handle = setInterval(() => print('repeating...'), 1000)

  
The built-in setInterval() function can be used to call a function repeatedly...
>>>
setTimeout(() => { clearInterval(handle); print('cleared'); }, 3100);

  
...until stopped with clearInterval(). A similar clearTimeout() function is available to cancel setTimeout() calls.
>>>
handle
2
The handle value returned by setTimeout() and setInterval() is required to cancel the calls. It is a good idea to store this value.
>>>
setTimeout(() => print('immediate'), 0);

  
The setTimeout() function is sometimes called with a zero delay (same as omitting the delay). This results in the function being executed as soon as possible (but not immediately). It is commonly used in event handlers to allow a browser event to finish processing before performing an action.
>>>
function callLater(millis, func, ...args) {
    setTimeout(func.bind(null, ...args), millis);
}
callLater(123, print, 'one', 2, 'three')

  
A common pattern is to wrap setTimeout() in a function to make it easier to work with. But thanks to arrow functions, variadic arguments and bind(), this is hardly needed anymore.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.