Question aksed in Inteview : you have to write an Javscript code to print number in increasing order in each 1 secound differ or print num like at 1 sec- 1 , 2 sec -2 , 3 sec -3 … n sec -n.
sr | Time out | Output |
1 | 1 | 1 |
2 | 2 | 2 |
3 | 3 | 3 |
4 | 4 | 4 |
5 | 5 | 5 |
6 | 6 | 6 |
Usually, the developer who answers this type of question often provides a solution quickly, which Looks correct but produces the wrong output.
Code :
Output Will Be Get is :
Why it Happen ?
The reason behind the output we are getting is closure. I assume you know what closure is and how closures work. If you don’t, please read our blog on closure by searching on our platform Nileshblog.tech.
How The code is Executing ?
- For Loop:
- Iterate from i = 1 to i = 5.
- Set Timeout Function inside Loop:
- For each iteration, schedule a setTimeout function.
- The function inside setTimeout logs the current value of i after a delay of i * 1000 milliseconds.
- Closure Concept:
- Inner function has access to outer function’s variables, including i.
- Call Stack Execution:
- NileshBlog is called.
- setTimeout functions are scheduled but not executed immediately.
- Loop completes and call stack is cleared.
- SetTimeout Delays:
- First setTimeout has 1-second delay, second has 2 seconds, and so on.
- Execution of setTimeout Callbacks:
- After delays, callback functions inside setTimeout are pushed into the call stack.
- Logging:
- Callbacks log the value of i, referencing the same i through closure.
- Final Log:
- “NileshBlog.Tech” is logged after loop completes and timeouts are scheduled.
Correct Approach to solve this problem ?
There are many approach to solve , we discuss here are two . first is just by simply replacing the let with constant.reason behind is this let create it seprate memory so that in every iteration it has uniques i copy.
1st appraoch :
Code:
function NileshBlog(){
for(let i=1;i<=5;i++){
setTimeout(function(){
console.log(i);
},i*1000);
}
console.log("NileshBlog.Tech");
}
//output
Nileshblog.Tech
1
2
3
4
5
Execution of Appraoch :
- For Loop:
- A for loop is used to iterate from 1 to 5.
- setTimeout Function:
- Inside the loop, setTimeout is used to log the value of i after a delay.
- The delay is set to i * 1000 milliseconds.
- Closure:
- setTimeout is a function that takes a callback function as its first argument.
- The callback function (function(){ console.log(i); }) forms a closure because it “closes over” the variable i.
- Execution of setTimeout:
- setTimeout is asynchronous, so it doesn’t block the execution of the loop.
- The loop continues to run, and each iteration schedules a new asynchronous task to log the value of i after a specific delay.
- Log “NileshBlog.Tech”:
- After the loop, console.log(“NileshBlog.Tech”); is executed.
- Execution Result:
- The numbers from 1 to 5 are logged after respective delays.
2 Approach : UsingFunction (Which create it seprate space /local executing context)
if you dont have knowledge about how the javascript is executed in backed you can read our blog on Javascript execution in backend or what is Execution context and excution context types ?.We understand that for every individual function, it creates its local execution context on top of the parent or global execution context. Therefore, in each iteration, it creates its own local space or space for its variables. Consequently, each setTimeout contains a separate and unique value of i for that iteration.
Code :