The setTimeout() Function in Angular

Rana Hasnain Khan Dec 21, 2022 Dec 04, 2021
  1. setTimeout() Function in Angular Using IIFE and Function Recursion
  2. setTimeout() Function by Passing List of Values in Angular
The setTimeout() Function in Angular

We will introduce Angular’s setTimeout() function using Immediately Invoked Function Expression (IIFE) and function recursion. We will also introduce Angular’s setTimeout() function by passing a list of times we want to wait and iterate them recursively.

setTimeout() Function in Angular Using IIFE and Function Recursion

We can use the setTimeout() function for various reasons. It is best to allow Angular to run change detection once, between the actions that we would otherwise perform synchronously.

setTimeout() is a native JavaScript function that sets a timer to execute a callback function, calling the function once the timer is done.

A simple setTimeout() function example:

let i = 0;
let max = 5;
(function repeat(){
  if (++i > 5) return;
  setTimeout(function(){
    console.log("waited for: " + i + " seconds");
    repeat();
  }, 1000);
})();

Output:

setTimeout Function In Angular Using IIFE And Function Recursion

In the above code block, we defined an integer i and max and used a repeat function to repeat our timeout until the condition is met.

If i values get greater than max, this loop will break. If the value of i remains under the max value, it will repeat every 1s and print waited for: 1 to 5 seconds.

setTimeout() Function by Passing List of Values in Angular

If we have a list of values for which we want our program to wait and execute the callback function, we can set our function to pass an array as a parameter and run until the array is complete.

Example Code:

let waitList = [5000, 4000, 3000, 1000];

function setDelay(times) {
  if (times.length > 0) {
    // Remove the first time from the array
    let wait = times.shift();
    console.log("Waiting For: " + wait/1000 + " seconds");
    
    // Wait for the given amount of time
    setTimeout(() => {
        console.log("Waited For: " + wait/1000 + " seconds");
        // Call the setDelay function again with the remaining times
        setDelay(times);
    }, wait);
  }
}

setDelay(waitList);

Output:

setTimeout Function By Passing List Of Values In Angular

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article - Angular Function