Back to Home

Scheduling: setTimeout and setInterval

We may decide to execute a function not right now, but at a certain time later. That’s called “scheduling a call”. There are two methods for it: - setTimeout allows us to run a function once after the interval of time. - setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval. These methods are not a part of JavaScript specification. But most environments have the internal scheduler and provide these methods. In particular, they are supported in all browsers and Node.js.

setTimeout

func|code

Function or a string of code to execute. Usually, that’s a function. For historical reasons, a string of code can be passed, but that’s not recommended. delay

The delay before run, in milliseconds (1000 ms = 1 second), by default 0. arg1, arg2…

Arguments for the function For instance, this code calls sayHi() after one second: With arguments: If the first argument is a string, then JavaScript creates a function from it. So, this will also work: But using strings is not recommended, use arrow functions instead of them, like this: // wrong! setTimeout(sayHi(), 1000);

Canceling with clearTimeout

A call to setTimeout returns a “timer identifier” timerId that we can use to cancel the execution. The syntax to cancel: In the code below, we schedule the function and then cancel it (changed our mind). As a result, nothing happens: As we can see from alert output, in a browser the timer identifier is a number. In other environments, this can be something else. For instance, Node.js returns a timer object with additional methods. Again, there is no universal specification for these methods, so that’s fine. For browsers, timers are described in the timers section of HTML Living Standard.

setInterval

The setInterval method has the same syntax as setTimeout: All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time. To stop further calls, we should call clearInterval(timerId). The following example will show the message every 2 seconds. After 5 seconds, the output is stopped:

Nested setTimeout

There are two ways of running something regularly. One is setInterval. The other one is a nested setTimeout, like this: The setTimeout above schedules the next call right at the end of the current one (*). The nested setTimeout is a more flexible method than setInterval. This way the next call may be scheduled differently, depending on the results of the current one. For instance, we need to write a service that sends a request to the server every 5 seconds asking for data, but in case the server is overloaded, it should increase the interval to 10, 20, 40 seconds… Here’s the pseudocode: And if the functions that we’re scheduling are CPU-hungry, then we can measure the time taken by the execution and plan the next call sooner or later. Nested setTimeout allows to set the delay between the executions more precisely than setInterval. Let’s compare two code fragments. The first one uses setInterval: The second one uses nested setTimeout: For setInterval the internal scheduler will run func(i++) every 100ms: Did you notice? The real delay between func calls for setInterval is less than in the code! That’s normal, because the time taken by func’s execution “consumes” a part of the interval. It is possible that func’s execution turns out to be longer than we expected and takes more than 100ms. In this case the engine waits for func to complete, then checks the scheduler and if the time is up, runs it again immediately. In the edge case, if the function always executes longer than delay ms, then the calls will happen without a pause at all. And here is the picture for the nested setTimeout: The nested setTimeout ensures a minimum delay (100ms here) between the end of one call and the beginning of the subsequent one. That’s because a new call is planned at the end of the previous one. // the function stays in memory until the scheduler calls it setTimeout(function() {…}, 100);

Zero delay setTimeout

There’s a special use case: setTimeout(func, 0), or just setTimeout(func). This schedules the execution of func as soon as possible. But the scheduler will invoke it only after the currently executing script is complete. So the function is scheduled to run “right after” the current script. For instance, this outputs “Hello”, then immediately “World”: The first line “puts the call into calendar after 0ms”. But the scheduler will only “check the calendar” after the current script is complete, so “Hello” is first, and “World” – after it. There are also advanced browser-related use cases of zero-delay timeout, that we’ll discuss in the chapter info:event-loop. let start = Date.now(); let times = []; setTimeout(function run() { times.push(Date.now() - start); // remember delay from the previous call if (start + 100 < Date.now()) alert(times); // show the delays after 100ms else setTimeout(run); // else re-schedule }); // an example of the output: // 1,1,1,1,9,15,20,24,30,35,40,45,50,55,59,64,70,75,80,85,90,95,100

Summary

let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)
Example:

Follow the lesson from Microsoft Web-Dev-For-Beginners course

Tags: web,development