I've looked around trying to understand how SetInterval
but only found how to use it. I already know it's functionality, I'm just curious about how it's able to run something on a separate thread when JS doesn't support threading(at least that's what I read).
I hope I formulated the question properly.
Thanks.
setInterval does not run anything on a different thread. It schedules something to run at certain times provided the JS runtime is idle at that time. The infinite loop will prevent the function from running, because the JS runtime is stuck in the loop.
The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .
This property can be used in the callback of the setInterval() function, as it would get immediately executed once and then the actual setInterval() with this function will start after the specified delay.
setInterval will run the function sendMessage every second (1000 ms).
setInterval
does not run anything on a different thread. It schedules something to run at certain times provided the JS runtime is idle at that time.
You can try out this behavior with something like this:
setInterval(function(){ alert("Hello"); }, 1000);
while (true) { }
The infinite loop will prevent the function
from running, because the JS runtime is stuck in the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With