Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is setTimeout implemented in the javascript interpreters or timers in general?

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

like image 617
alvatar Avatar asked Sep 06 '25 07:09

alvatar


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!