The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

Syntax

setTimeout(functionRef)
setTimeout(functionRef, delay)
setTimeout(functionRef, delay, param1)
setTimeout(functionRef, delay, param1, param2, /* …, */ paramN)

Parameter

delay
Delay is used to set a timer in milliseconds and wait until the timer is not complete then function or code will evaluate or execute. This is optional parameter in settimeout syntax. If we do not pass the value then it should be by default set to 0.

functionRef
We can write function with data execution after the timer has been completed or expired.

param1, param2, …, paramN
We can pass the extra arguments or parameters to the function ref. This is optional parameters in set timeout method.

Return Value

Set timeout will return the timeoutID and it is used to clear the timeout to cancel the timeout.

Examples

1 setTimeout(functionRef)

// Function Style 1

setTimeout(() => {
  console.log("Delayed for 0 second.");
});

// Function Style 2

const counterFn = () => {
   console.log("Counter function")
}
setTimeout(counterFn)

2 setTimeout(functionRef, delay)

const counterFn = () => {
   console.log("Counter function delayed for 1 second")
}
setTimeout(counterFn, 1000)

3 setTimeout(functionRef, delay, param1)

const counterFn = (arg) => {
   console.log("Counter function delayed for 1 second with params", arg)
}
setTimeout(counterFn, 1000, "Parameter value")

4 setTimeout(functionRef, delay, param1, param2, …. paramN)

const counterFn = (...arg) => {
   console.log("Counter function delayed for 1 second");
   console.log("All parameters will get into array");
   for(let i=0; i < args.length; i++){
      console.log("Parameter ", argos[i]);
   }
}
setTimeout(counterFn, 1000)

Statement – SetTimeout with Loop, Await & One by One Asynchronous Call

We have two solutions to solve this problem statement

Solution 1 – Using recursion method & await asynchronous call

const delay = [3000, 1000, 4000];


let i = 0;

(function recursiveFn(){
    if(i >= delay.length) {
        console.log("Exit recuresive function");
        return;
    }
    setTimeout(async () => {
        console.log("Delayed for ", delay[i]);
        i++;
        recursiveFn();
     }, delay[i]);
})(); //Using IIFE (Immediately Invoked Function Expression)

In the 1st solution we have used a recursive method using IIFE. The repeat call of the recursive function when the set timeout expires.

Solution 2 – Using IIFE for loop & await asynchronous call

const delay = [3000, 1000, 4000];

(async function (){
    for(let i=0; i < delay.length; i++){
        await promiseFn(delay[i]);
        console.log("Delayed for ", delay[i]);
    }
    console.log("For loop exit", duration);
})();

function promiseFn(val) {
    return new Promise(resolve => setTimeout(resolve, val));
}

In this 2nd solution using a for loop we can achieve the same result. Using this promise method by adding set timeout into promise and resolve the method to await till the set timeout does not expire.

Both the solution execution performance tests are almost the same. We can use any of these solutions to implement the logic in our code.

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.

Example of IIFE –

(function () {
  // ...
})();

(() => {
  // ...
})();

(async () => {
  // ...
})();

Support On Demand!

                                         
Angular