Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DoEvents in JavaScript

Tags:

jquery

I have the following:

$('body, a').addClass('cursor-wait');
for (var I=0, L = myArray.length; I < L; I++) {
   // tight loop here
}
$('body, a').removeClass('cursor-wait');

But I'm not sure the cursor:wait icon is showing up immediately.

Q: Is there a way to tell say "DoEvents" in JavaScript, such that I know that the DOM is being updated before it goes into the loop?

Maybe using the setTimeout method.

like image 956
Phillip Senn Avatar asked Apr 11 '11 20:04

Phillip Senn


1 Answers

Here's what is happening:

The browser instance handling your page is single threaded. The change to the DOM happens right away. However, while your script is running, the browser is blocked and not able to run its layout manager which updates the page according to the CSS classes have changed. You are correct that setTimeout is the best way to cede control to the layout manager and see your changes on the screen. You don't even need to set a delay, simple act of calling setTimeout allows the layout manager a chance to redraw the page.

$('body, a').addClass('cursor-wait');
setTimeout(function () {
    for (var I=0, L = myArray.length; I < L; I++) {
       // tight loop here
    }
    $('body, a').removeClass('cursor-wait');
});
like image 101
EMI Avatar answered Nov 13 '22 16:11

EMI