DEV Community

loading...

setTimeouts inside a for loop

helpmichaelcode profile image HelpMichaelCode ・1 min read

So I've encountered a problem that I've been trying to solve for a week now... Say I have a setTimeout inside a for loop. Inside the setTimeout function I have -> setTimeout(callback, timer, parameters of the callback). My problem is that, the values of the parameters aren't always the values that I am expecting and it seems to be that their values are always getting overwritten on each execution. My question is, how can I avoid this in a way where the values of the parameters aren't overwritten. I know this has something to do with scope but I'm not too sure how to approach it or do it.

Discussion

pic
Editor guide
Collapse
kosich profile image
Kostia Palchyk

Hi, Michael! This is a classic closures question for JS!

See this stackoverflow thread for details:
stackoverflow.com/questions/522628...

Ping me if you still have questions πŸ™‚