Search code examples
javascripttimerevent-handlingdom-events

What is the priority of event handling and timer servicing in JavaScript?


I am trying to understand the execution priority of Javascript. I have a code where a timer runs to callback a function after 15 seconds. However, an event might occur just before that and the even handler function may be called.

  1. What happens if the timer goes off when the event is being serviced?
  2. Does JS interrupt the event and service the timer and come back to the event? From ejohn's blog on How JavaScript Timer Work, this is probably not what happens.
  3. What happens if the timer goes off when the even is being serviced and the event handler executes clearTimeout(theTimerThatJustWentOff)? Will the timer service routine run after we exit the event handler?
  4. How much will these behaviours vary across browsers?

I am not asking what happens in a race condition of two asynchronous events. In my case, one has occurred and is being serviced while the second occurs.


Solution

  • Javascript runs single-threaded. That should answer your questions. So

    1. the timer doesnt go off while its running. When your function finishes or when it yields (by doing a continuation with setTimeout for example) your trigger will run again.
    2. no.
    3. no. - see 1.
    4. Shouldn't vary.