I don't quite understand how timers work in Javascript. JS is single threaded so code runs and e.g. user clicks the button the click is added to the queue. The queue was empty so the queue looks like that:
[click]
That will be executed as soon as our code currently running finishes is that right? Lets say the same code still running though and is not finished just yet and its schedules setTimeout(fn,3000)
.
Now I'm not sure if I got this right. This fn
is not added to the queue but will fire at some point close to 3000ms from this very moment (NOT from when this code execution ends). If at this time when that event wants to fire (in around 3000ms from now) other code is executing (maybe [click] from above) this fn
will be put at the end of the queue then.
Now back to our original running code, [click] is in a queue and code runs further. Now our running code changes style property of some element in DOM and adds the border. This change will have to be done when browser will refresh UI. It will not be visible immediately as JS is running some other code and so is added after the click so the queue looks like that now:
[click] [UI refresh - it will change border amongst other things possibly]
So now queue contains two events to be called when currently run JS ends. It will call [click] and user still will not see the change in the border our earlier code requested. When click is finished next event from the queue will jump in which is UI refresh. It will do whole bunch of drawing probably, including our border change we requested when earlier code run.
If during the time when click event is being executed or when UI makes changes to the display and is redrawing the screen the timer we scheduled fires, fn
will be added to the queue and executed as soon as possible.
Is my understanding correct? If someone could clarify if I misunderstood something and explain where I got it wrong that would be great. Once I clarify this I will extend this question to setTimeout(fn,0)
trick as this what really gets me confused even further.