javascript - javascript timer - javascript wait function - school of programming

Javascript Timers and Javascript Wait Functions: Handling Execution Times

Dynamic content, or content that changes when a user interacts with a web page, is an integral part of the modern web experience. Javascript provides web users with a more engaging web experience by making it easy to create dynamic content.

A key aspect of creating dynamic content is making sure that the changing parts of a web page happen at the proper time. When dynamic Javascript effects occur at the wrong times, parts of a web page can become inaccessible, too much content can crowd the screen at once, and users can experience other problems.

The Javascript standard provides two different functions to control dynamic timing: setTimeout() and setInterval(). Each function defines specific times that dynamic events should happen; they work differently and are best used in different contexts..

Importance of Javascript Timers

Javascript “timers” and Javascript “wait functions” are two common names for the same thing: Javascript functions that pause a program’s execution. Pauses are rarely necessary for calculations that the user never sees, but are often vital to giving users a smooth experience on web pages.

For example, if you are on a website that contains a picture flipbook, timers are how those flipbooks work. Without a timer, two pictures would just change from one to the other immediately without any animation between them. Each change that you see in the animation results from a Javascript timer.

All Javascript timers work over both small and large time blocks. Small time intervals create smooth animation, similar to frames in a movie that appear rapidly, one after another. Large time intervals give users time to digest information before moving on to something else, like reading a book page before the next page loads.

Javascript timers are a relatively modern addition to Javascript, so they don’t work in many old browsers, like Internet Explorer 9 and below. Longer functions that approximate timers, called polyfills, are available across the web, but the percentage of web users that use older browsers without these functions are very small (currently less than 2%).

Most comprehensive polyfills that compensate for many older browsers are 50 lines of code or more; too long for inclusion here. For the increasingly rare occasions that you may need a polyfill for one of the Javascript timer functions, there are many reliable examples on GitHub, in code tutorials, and offered by private developers.

The setTimeout() Function

The setTimeout() function implements a delay before executing a specific Javascript function. It requires two parameters: a post-delay function to be run and the delay time.

The post-delay function must be defined in the Javascript file before being called by setTimeout(). The delay time is a whole number (integer), specified in milliseconds (1/1000th of a second.

// After a delay, say "Hi!"
function delayedFunction() {
    console.log("Hi!");
}

// Run delayedFunction() after a 2000 millisecond (2 second) delay
let timer = setTimeout(delayedFunction, 2000);

The post-delay function may need parameters too. Pass parameters to the function by adding them to the setTimeout() invocation. The first two parameters passed to setTimeout() are consumed and additional parameters, which can be any valid Javascript type, are passed in.

// After delay, say a personalized "Hi"
function delayedFunction(a, b) {
    console.log("Hi " + a + " " + b + "!");
}

// Run delayedFunction() after a 2000 millisecond (2 second) delay
let timer = setTimeout(delayedFunction, 2000, "John", "Doe");

The setTimeout() function returns the internal ID of the post-delay function, useful when the delay must be cut short by clearTimeout().

clearTimeout(timer); // stop the delay set previously

The setInterval() Function

The setInterval() function, like setTimeout(), implements a delay before executing a post-delay function. While the setTimeout() function executes its post-delay function exactly once, setInterval() continues calling its function at intervals until explicitly stopped.

setInterval(), like setTimeout(), requires two parameters: a post-delay function and a delay time. Subsequent parameters are passed to the post-delay function.

Be mindful of which function you’ve chosen, and stay consistent. Do not confuse setInterval() and setTimeout(), nor clearInterval() and clearTimeout().

// After delay, a personalized "Hi"
function delayedFunction(a, b) {
    console.log("Hi " + a + " " + b + "!");
}

// Continuously run delayedFunction every 2000 milliseconds
let timer = setInterval(delayedFunction, 2000, "John", "Doe");

// (sometime later in the code)
// Stop the previously set timer from being called
clearInterval(timer);

Conclusion

More advanced than basic Javascript, Javascript timing functions give developers visible control over a user’s web experience. 

Use setTimeout() to run a function after a single delay, and cancel that delay at any time with clearTimeout(). Use setInterval() to run a function many times with a delay before each execution, and cancel those repeated executions with clearInterval().

Start Learning

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni