views:

15

answers:

1

How setTimeout in Javascript works at the low level? Is there exist some hardware alarm clock? Or interpreter (through system) just asks periodically what time is now?

+1  A: 

All that's specified is the language-level effects. There's no requirement that it work a specific way at a low level. Doing so would require some intrusive policy on what functions have to exist in your language of choice before you could create a Javascript interpreter.

Generally, most OSes do have a system timer that ticks X times a second, and an interpreter will either set up a timer to fire an event or send a signal after so many ticks, or run a separate thread that sleeps til it's time to process a timeout. At that time, the interpreter will set things up so that the event handler is the next thing to run. But you should not rely on any particular behavior, as it is an implementation detail (and could fail spectacularly if you're not running your code in a browser you developed for).

cHao
ok, but how timers work in OS? How OS know when to do next timer tick? How OS know when to fire event? My question is general and not actually related to a particular language. The question is more about CPU architecture, I think.
Dan
Most machines have a mechanism to interrupt the CPU X times a second. The OS sets things up to respond to those interrupts and increment a counter, and usually will check if there's any process/thread that was waiting for the counter to reach a given value (and start/resume it if so). In order for this to make more sense, you'll want to understand hardware interrupts.
cHao
Thanks, things have become more clear to me.
Dan