28

How is a function called after a time has passed implemented in javascript or any other interpreted language?

In other words, is there a loop behind in the javascript interpreter that checks all the time a list of timers, or is there any particular way that the operating systems handle this?

Thanks

alvatar
  • 3,340
  • 6
  • 38
  • 50

1 Answers1

2

You maintain a sorted data structure (for instanced a priority queue) that allows you store (timeout, callback). This allows you quickly figure when the next timeout is. The key aspects is how do we wait, and how do we interrupt the wait to schedule a new callback.

  1. You can wait by sleep(3)'ing in a thread and when done you invoke the callback. When you need to schedule a new (timeout, callback) send a signal(2) or pthread_cond_signal(3) to the thread.

  2. Similar to above, but you use pthread_cond_timedwait(2) and the thread wakes up when the timeout occurs, or when the condition variable triggers to schedule a new callback.

  3. You can schedule an alarm(2) and continue whatever other tasks you were doing. When the alarm goes off it will send a signal to your process and you can you invoke the callback when convenient. To schedule a new timeout you set a new alarm which will cancel the old.

  4. You use select(2)/poll(2)/epoll_*(2) with a timeout. When the timeout occurs you invoke the callback. To schedule a new callback you write a byte to pipe that is used specifically to have select/poll/epoll return so you schedule a new event. chrome/node/v8, for instance, uses this method just wrapped in a compatibility layer (see How is setTimeout implemented in node.js).

  5. Like above but instead of using the timeout argument, you can use a timerfd_create(2) which is a file descriptor delivers time expiration.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • It appears all the solutions rely on the operating system to provide this functionality to avoid busy looping in the application. Therefore it's not possible to create timer mechanism in-process without busy looping. And I suspect even the operating system itself depends on hardware to enable this. – CMCDragonkai Jul 22 '22 at 04:04
  • See https://cs.stackexchange.com/questions/112983/how-are-hardware-interrupts-handled. – Allan Wind Jul 23 '22 at 17:43