DEV Community

Discussion on: Wait for it: Implementing a sleep() function in JS

Collapse
 
vittostack profile image
Vitto Rivabella

Yeah, one quick question, does Js implements something like the Python GIL?

Thread Thread
 
dsasse07 profile image
Daniel Sasse • Edited

From my understanding of GIL from your post, there is something similar. JS uses a single threaded call stack to resolve functions so the most recently invoked function must be resolved before the previous one. Function execution proceeds line by line. When utilizing setTimeout and setInterval like I described above, it actually adds the callback function passed to those to a separate call stack that has priority at during run time. When the timer is up, these functions execute before returning to the main call stack.

This is why I couldn't just use a timeout by itself, because the main thread would proceed and finish execution without waiting for the timeout stack to execute and return its value. Hope that helps!

Thread Thread
 
tuanfrontend profile image
Eden Tuấn

Hello