Can you pass extra arguments to setTimeout in JavaScript?
Yes. setTimeout(fn, delay, arg1, arg2, ...) passes the extra arguments to the callback. This can be used to capture the current value of i in a loop without let or an IIFE.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in setTimeout and Closures in JavaScript Explained
3, 3, 3. var is function-scoped, so all callbacks share one i. By the time the callbacks run (after the loop, via the event loop), i is 3. All three callbacks log 3.
Use let instead of var (each iteration gets a fresh binding). Or use an IIFE to capture the current value of i as a parameter. Or pass i as an extra argument to setTimeout.
Because let is block-scoped and creates a fresh binding per iteration. Each callback closes over its own copy of i, which holds the value for that iteration. With var, all callbacks share one i.
Still have questions?
Browse all our FAQs or reach out to our support team
