Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does SetInterval run things on a seperate thread? How does the method work?

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.

like image 224
José Corretjer-Gómez Avatar asked Apr 30 '15 16:04

José Corretjer-Gómez


People also ask

Does setInterval run on a seperate thread?

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.

How does setInterval method work?

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() .

Does setInterval execute immediately?

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.

How many times does setInterval run?

setInterval will run the function sendMessage every second (1000 ms).


1 Answers

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.

like image 104
Timothy Shields Avatar answered Sep 30 '22 23:09

Timothy Shields