setTimeout( ) + Closures in JavaScript π


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 na
me
β 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 executionClosures+remember outer scope
Use
let
or closures to fix async loop issuesWorks great for animations & UI effects
π’ follow me for more real-world JavaScript tips from my internship journey.
π Devsync
Subscribe to my newsletter
Read articles from ronak wanjari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
