How to resolve setTimeout() inside for loop

How to resolve setTimeout() inside for loop

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. It is used to fire a piece of code after the specified timers expire (run a function once after the interval of time).

Syntax: setTimeout(function, milliseconds, [param1], [param2], ...)

setT.png

As shown in the above piece of code, the callback function is executed after the specified time interval expires. Now let’s see how a setTimeout executes inside a JavaScript for loop.

set.png

Problem: When you execute the above piece of code, you will see the last value of i being printed each time on setTimeout callback execution.

What's actually going on in the loop?

The setTimeout function callback isn’t triggered until the for loop execution has completed. When the for loop has finished executing the value of i is 7. Now when the setTimeout call begins to execute it uses the last set value of i which is 7. Hence 7 is printed in all the setTimeout callbacks.

How can this be resolved?

  • Using the let keyword

Using the ES6 let keyword inside the for loop, creates a separate scope for each iteration making it possible to print the consecutive variable value.

letK.png

  • Using IIFE (Immediately Invoked Function Expression)

IIFE can be used to create a new scope for each setTimeout callback without polluting the global scope. Simply wrap up the setTimeout code inside an IIFE.

iife.png

  • Setting the setTimeout() within a function outside the for loop

Set the timeout from within a function outside the for loop then call the function from inside the loop.

func.png

Feel free to share your tips and experiences too!

Happy Coding...