Reputation: 13184
Let's consider such html:
<div class="my-class"></div>
and js (using jQuery
):
var interval = 10;
setInterval(function(){
//I toggle .my-class 'extra-class' every 10ms
$(".my-class").toggleClass("extra-class");
}, interval);
//then outside interval I'm doing some action on the same item as interval does
$(".my-class").each(function(){
var t = $(this).addClass("extra-class"); //I'm sure I've added extra-class
//but now I'm doing some action longer than 10ms
for (var i = 0; i < 10000; i++) {
//some long action here that could take more than 10ms
};
//can I still be sure now that it have extra-class added in THIS scope
//it was added in this scope but it is toggled all the time
console.log( t.hasClass("extra-class") );
});
What happens is:
extra-class
on .my-class
all the time every 10ms
scope
when I'm sure I've added extra-class
to some itemscope
I'm doing some action that takes more time
than 10ms
scope
?If I can be sure - does it mean that interval is waiting for my scopes to finish even if more time passed from last interval than it should wait? What if some single scope would take 100x times more than interval time?
If I can't be sure - does it mean that interval actions can be fired in the middle of my scope code?
Upvotes: 2
Views: 183
Reputation: 5958
// (A)
var t = $(this).addClass("extra-class"); //I'm sure I've added extra-class
// (B)
// Some long action here that could take more than 10ms
...
// (C)
// can I still be sure now that "this" still has class "extra-class"?
Yes. Since JavasScript is single-threaded, there's only one thread that runs through A
, B
and then C
. No other JavaScript code will be executed until the currently executing code has finished.
Even if you have set a setInterval
in order to execute a function at a given time, that function will only run on time if the single thread is free. Otherwise, it will have to wait until the single thread has finished executing everything else.
Upvotes: 2