📌 JavaScript

Javascript setTimeout and setInterval all you need to know

January 05, 2022

Javascript has so many global methods and properties that can be accessed in any part of the JS code. setTimeout and setInterval are two of the most essential JS methods.

setTimeout and setInterval are attached to the window object, they can be accessed prefixing with window object like window.setTimeout() and window.setInterval() or more often without the prefix.

Global methods and properties need not be prefixed with window object and only if in cases you want to make sure that you are in browser environment and want to access global method or property, then prefix with window object.

The way Javascript setTimeout and setInterval work are very similar. These are used to work with the timing or scheduling of functions. 

Javascript setTimeout

The setTimeout Javascript method sets a timer and executes a function passed to it once the timer expires.

Basically, the setTimeout method takes a function or the function reference as the first argument, followed by the optional arguments, delay, and the arguments to the function. Whenever the delay gets expired, the function gets executed or called.

setTimeout(function() {}, delay, arg1, arg2, ...);

Let's see it by a simple example.

setTimeout(() => {
}, 2000); 
// After 2 seconds logs:
// Hi

In the above example, after 2 seconds text gets logged in the console. The delay argument in the setTimeout method should be in milliseconds. If there's no delay given, 0ms will be the default delay.

const getData = (type = 'json') => {
  console.log('Getting data of type ' + type);
setTimeout(getData, 5000, 'markdown');
// After 5 seconds logs:
// Getting data of type markdown
// Logs immediately:
// Getting data of type json

In the above code snippet, we can see that the third argument in the setTimeout is passed to the getData function. All arguments other than the first two gets passed to the function, in this case, it is getData

If in case if we want to stop the function from being executed before the timer expires, we can do that by using the clearTimeout global method of Javascript.

Every setTimeout method returns a unique timer ID using which we can clear that scheduled timer.

const logger = () => {
  console.log('Logging details');
const timerId = setTimeout(logger, 5000);

// If called before the timer expires, logger function won't be executed

In the above code snippet, we can see the clearTimeout being called before the timer expires as a result setTimeout won't execute the logger function. 

clearTimeout can be called with the timer ID, inside any function based on different conditions to stop setTimeout executing the function. 

Points to note for setTimeout:

  1. setTimeout is an asynchronous function which means the code that comes after it won't wait for it to complete.
  2. The first argument of setTimeout takes a function reference which it calls once the timer expires, but often people call the function instead of passing the reference, as a result, whatever is returned from the function is executed by the setTimeout
    const greet = function() { console.log('Hi')};
    setTimeout(greet(), 5000); // greet gets executed without delay, it returns undefined as first argument to setTimeout
    setTimeout(greet, 5000);  // greet gets executed after 5 seconds
  3. The this keyword will not behave as expected inside setTimeout. In such situations, you can use arrow functions as they bind this to the function scope, they are created in.
    const person = {
      name: 'John',
      greetFunc: function () {
        setTimeout(function () {
          console.log(`Hi, ${this.name}`);
        }, 2000);
      greetArrow: function () {
        setTimeout(() => console.log(`Hi, ${this.name}`), 2000);
    person.greetFunc(); // Hi, undefined
    person.greetArrow(); // Hi, John
  4. setTimeout with 0ms will not be executed immediately as it looks. It is executed after all the script is run, because it's an asynchronous function that is sent to the event loop before getting to the call stack.
    console.log('First statement');
    setTimeout(() => console.log('Second statement'), 0); // delay can be omitted it's the default value
    console.log('Third statement');
    // Log result(observe the order):
    // First statement
    // Third statement
    // Second statement

Now let's get into the setInterval of Javascript.

Javascript setInterval

The setInterval Javascript method calls a function passed to it at every interval of time until unless it is stopped.

So it is similar to the setTimeout, but instead of calling the function once it keeps calling it at regular intervals until it gets stopped.

The seteInterval method takes a function or a function reference as the first argument, followed by the optional arguments, delay(time interval), and the arguments to the function. The function gets executed or called, with a fixed time delay between each call.

setInterval(function() {}, delay, arg1, arg2, ...);

Let's see it with a simple example

setInterval(() => {
}, 2000); 
// After every 2 seconds it logs:
// Hi
// Hi
// ....

In most situations, it is important to stop calling the functions passed to the setInterval.

Similar to the setTimeout, setInterval returns an interval ID that uniquely identifies the interval(nothing but the setInterval instance).

Similar to clearTimeout, setInterval has clearInterval, calling it with the interval ID will clear or stop the setInterval instance from further calling the passed function.

const intervalId = setInterval(() => {
}, 2000);

setTimeout(() => clearInterval(intervalId), 5000);
// Hi
// Hi
// By 5th second clearInterval stops the setInterval instance

Just like in setTimeout we can pass the arguments to the function we want to call in setInterval after the delay argument.

const greet = (name) => {
  console.log(`Hi, ${name}`);
const intervalId = setInterval(greet, 2000, 'John');
setTimeout(() => clearInterval(intervalId), 5000);
// Hi, John
// Hi, John

So all the points that we discussed in the setTimeout section will hold true for the setInterval

setTimeout is also asynchronous, function reference has to be passed as the first argument instead of calling it and this keyword will not behave as expected similar to the setTimeout, so prefer using arrow functions. 

So that's all you need to know about setInterval method in Javascript.

Let's see how we can create setInterval using setTimeout.

Nested setTimeout

We can use setTimeout to create a setInterval like method with variable delays. Nested  setTimeout in fact helps to set precise delays between function executions than setInterval

Let's see an example to create a setInterval like method using nested setTimeouts.

// const timer = setInterval(() => console.log('Hi'), 100); // Hi, Hi,...

//setInterval equivalent using nested setTimeout

let delay = 100;
let timerId = setTimeout(function greet() {
  // delay can be varied as per our requirements
  // if(condition) delay = ...;
  timerId = setTimeout(greet, delay);
}, delay);

// Logs after every 100 milliseconds
// Hi
// Hi
// ...

If you try to experiment using setInterval and nested setTimeout, setInterval delays are not precise because it consumes some of the interval time in function execution and if the function execution takes more time than the delay, then you won't even see time delays between each function execution.

So for precise intervals between each function call, you should prefer using nested setTimeout over setInterval.

You should also keep in mind that, setTimeout and setTimeout do not guarantee exact time delays. The delays depend on CPU overload, background running processes in the browser window, etc. 

And that is all about Javascript setTimeout and setInterval. 

If you like receiving regular tips, tricks related to web development and technology then do follow on devapt-twitter @dev_apt