Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this behavior of setInterval imply multithreading behavior in Javascript?

In using javascript i noticed this thing. You can use

var i=0; 
var startingTime=new Date().getTime();
setInterval("foo()",1);
function foo() {
    i+=1;
    if ($("#foodiv").text()==i) {
        //we detected a doubled value (parallel execution)
        $("#repdiv").append("[repetition on "+i+"]");
    }
    $("#foodiv").html(i);
    $("#timediv").html(Math.floor((new Date().getTime()-startingTime)/1000));
}

but as i read and try myself the time is not 1ms , it's at least 10ms or something. In fact after 10 seconds, i have a value of i around 2300/2400 , and not 10000 as expected.

This is the minimum possible time factor for the procedure ??? certainly NO. If i try this :

<html><head>
<script language="javascript" type="text/javascript" src="jquery-1.4.min.js"></script>
<script type="text/javascript">

var i=0;
var startingTime=new Date().getTime();

setInterval("foo()",1);setInterval("foo()",1);setInterval("foo()",1);
setInterval("foo()",1);setInterval("foo()",1);setInterval("foo()",1);
setInterval("foo()",1);setInterval("foo()",1);setInterval("foo()",1);
setInterval("foo()",1);setInterval("foo()",1);setInterval("foo()",1);
setInterval("foo()",1);setInterval("foo()",1);setInterval("foo()",1);
setInterval("foo()",1);setInterval("foo()",1);setInterval("foo()",1);
setInterval("foo()",1);setInterval("foo()",1);setInterval("foo()",1);
setInterval("foo()",1);setInterval("foo()",1);setInterval("foo()",1);

function foo() {
    i+=1;
    if ($("#foodiv").text()==i) {
        //we detected a doubled value (parallel execution)
        $("#repdiv").append("[repetition on "+i+"]");
    }
    $("#foodiv").html(i);
    $("#timediv").html(Math.floor((new Date().getTime()-startingTime)/1000));

}
</script>
</head>
<body>
<div id="foodiv"></div>  (counter)
<br/>
<div id="timediv"></div> (seconds passed)
<br/>
<div id="repdiv"></div>
<br/>
</body>
</html>

The counter will go very fast, and after 10 seconds, i have a value of 12000 !!!!. That's for me is unexplicable, because the call is not executed in parallel (or at least we could have some doubled readed values of i for different calls, figuring in the repdiv div).

Can someone explain me that ? I know the cpu is very stressed by all those calls, but at least it speed up things surprisingly.

I read all your responses and the other quests in the forum, and they confirmed my thinking. But the real question is Why ! Why they set the limit to 15ms when i can do multiple sequential calls obtaining a time much lower ? I'm sure this multiple callback system is not good practice, but i can do it, and i potentially can saturate cpu load.

like image 469
mizar Avatar asked Oct 27 '10 21:10

mizar


People also ask

Does JavaScript support multithreading?

JS in browsers doesn't support multithreading in the event loop as it is not needed for 99.999% of the websites. The event loop handles everything seamlessly. For the remaining apps, devs can use web workers. Web Workers are a simple means for web content to run scripts in background threads.

How does setInterval work in JavaScript?

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

Why you should not use setInterval?

In case of time intensive synchronous operations, setTimeInterval may break the rhythm. Also, if any error occurs in setInterval code block, it will not stop execution but keeps on running faulty code. Not to mention they need a clearInterval function to stop it.


2 Answers

No, Javascript is single threaded. When you run setInterval or setTimeout, an event is generated which is then added to the browser's execution queue. So while you cannot guarantee that the code itself will run exactly when you want it to run, you can be sure that the event will be generated each time it is supposed to be generated. So in this case, you have 12 events that are being generated really close to each other. I notice that you've used 1 as the interval value. However, the minimum values in most browsers is around 15 (see here for more information.) The browser will run through the events in the order they are in the execution queue (in setInterval, the events try to play catch up. Look at the answer that Marcel linked to, for more details).

What this means is that in the first scenario you have one event generated every 15 or so milliseconds. So the counter is incremented more slowly. But in the second case, you have twelve events that are fired pretty close to each other every 15 or so milliseconds, and so the counter increments much faster.

like image 193
Vivin Paliath Avatar answered Sep 29 '22 18:09

Vivin Paliath


JavaScript timer values are set to at least 15ms in most browsers, even if a smaller value is given. AFAIK only Google Chrome uses 4ms. See also the accepted answer of How to determine the best "framerate" (setInterval delay) to use in a JavaScript animation loop? .

like image 31
smilingthax Avatar answered Sep 29 '22 18:09

smilingthax