💡 Did you know this about 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁()? Most developers use only two parameters — the callback and the delay. But here’s the twist — 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁() actually accepts a 𝘁𝗵𝗶𝗿𝗱 𝗮𝗿𝗴𝘂𝗺𝗲𝗻𝘁 👀 This third argument lets you pass values 𝗱𝗶𝗿𝗲𝗰𝘁𝗹𝘆 𝗶𝗻𝘁𝗼 𝘆𝗼𝘂𝗿 𝗰𝗮𝗹𝗹𝗯𝗮𝗰𝗸, saving you from those annoying 𝘀𝗰𝗼𝗽𝗲 𝗮𝗻𝗱 𝗰𝗹𝗼𝘀𝘂𝗿𝗲 𝗶𝘀𝘀𝘂𝗲𝘀 that often sneak in. Check out the examples below — they look almost identical, but their outputs tell a completely different story. #JavaScript #ReactJS #WebDevelopment #CodingTips
Loop 1 -------- - var is globally hoisted (common variable so shared among all block scope) - In each loop new block scope is created and timer is register & start for 1 seconds, Also prarally i value is incrementing - But loop completions is happen before 1 seconds & latest value of i is now i=5 (break the loop) - After 1 seconds expiration All 4 setTimeout() timer start executing and want to print i (but latest value of i is 5), so print 5 Loop 2 ------- - Same functionality - But in setTimout we pass a current value of i in that current block scope - So in console we accessing the current parameter, passed in that current scope (incremented value in that current scope). Summary : var is hoisted globally so that every have common variable Loop1 : - In each loop create block ({}) and parally increment the i (i++) Loop2 : - same but passing current i value in that current block scope ({})
Ah this is very useful. Many of us have been using setTimeout for years and still miss this part. That third argument can really save someone from headache especially with loops. Thanks for sharing, I’m definitely trying this out again.
Brilliant example! This showcases exactly how JavaScript handles closure snapshots inside async callbacks. By passing the loop variable directly through setTimeout’s third parameter, we bypass the deferred evaluation problem caused by var capturing the same reference each iteration.