Search code examples
javascriptcallback

How JS Engine knows whether there is a callback waiting to get executed?


From what I know, When there is an setTimeout, timer webAPI is called and once the timer finishes, the callback will be pushed to callback queue. once the call stack is empty, event loop picks up the message from callback queue and executes.

If setTimeout is of 1 hour and call stack is empty as it finishes executing the global execution context. Now there won't be any call back function in callback queue as it will pushed to queue once after timer API finishes (1 hour). Event loop checks the call stack whether it is empty and even in call back queue it will empty. How JS engine waits for 1 hour?

How js engine keeps track of call back function that are not in call back queue.


Solution

  • JS engine has what we call the event loop.

    Event Loop

    When you call setTimeout, the function schedules scheduling the execution of the callback via putting it into the callback queue. The callback queue will not push the functions into the event queue that were not yet scheduled to be executed.