setTimeout( ) + Closures in JavaScript πŸš€

ronak wanjarironak wanjari
2 min read

By Ronak Wanjari, Intern Devsync

Durning my internship at @DevSync, I kept running into a tricky combo in JavaScript β€” setTimeout() + closures. They seemed simple, but together, they can confuse even experienced devs, especially inside loops.

Let’s break it down simply πŸ‘‡


πŸ”Ή What is SetTimeout()?

setTimeout() is used to run code after a delay.

jsCopyEditsetTimeout(() => {
  console.log("Hello DevSync!");
}, 2000);

⏱️ The above code runs after 2 seconds.


πŸ”Ή what is a Closure?

A closure is when a function remembers variables from the scope it was created in.

jsCopyEditfunction outer() {
  let name = "DevSync";
  return function inner() {
    console.log(name);
  };
}

const greet = outer();
greet(); // DevSync

The inner() function still remembers name β€” that’s a closure.


πŸ”Ή Common Issue: Loop + setTimeout + var

jsCopyEditfor (var i = 1; i <= 3; i++) {
  setTimeout(() => console.log(i), i * 1000);
}
// Output: 4 4 4 ❌

Why? Because var is function scoped**,** and by the time the setTimeout() runs, the loop has finished β€” so i becomes 4.


βœ… Fix 1: Closure using IIFE

jsCopyEditfor (var i = 1; i <= 3; i++) {
  (function (x) {
    setTimeout(() => console.log(x), x * 1000);
  })(i);
}
// Output: 1 2 3 βœ…

Each loop creates a new scope with x.


βœ… Fix 2: Use let

jsCopyEditfor (let i = 1; i <= 3; i++) {
  setTimeout(() => console.log(i), i * 1000);
}
// Output: 1 2 3 βœ…

let is block scoped, so each iteration gets a fresh value.


πŸ’‘ Real-World Use: Typing Effect

jsCopyEditconst msg = "Hello DevSync!";
for (let i = 0; i < msg.length; i++) {
  setTimeout(() => process.stdout.write(msg[i]), i * 150);
}

Looks like someone is typing it out live on your screen ⌨️✨


πŸ”š Conclusion

Closures + setTimeout() is a powerful pattern for animations, delayed logic, and async loops. It’s one of those concepts I used and debugged often during my time at Devsync , and it made me better at writing clean, predictable JS.


βœ… Quick Recap:

  • setTimeout() = delay execution

  • Closures+remember outer scope

  • Use let or closures to fix async loop issues

  • Works great for animations & UI effects


πŸ“’ follow me for more real-world JavaScript tips from my internship journey.
πŸ”— Devsync

0
Subscribe to my newsletter

Read articles from ronak wanjari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ronak wanjari
ronak wanjari