JavaScript DoEvents

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 what the cursor is: the wait icon appears immediately.

Q: Is there a way to say โ€œDoEventsโ€ in JavaScript so that I know that the DOM is updated before it goes into a loop?

It is possible to use the setTimeout method.

+7
source share
3 answers

Here's what happens:

The browser instance processing your page is single-threaded. A change in the DOM occurs immediately. However, while your script is running, the browser is locked and cannot start its layout manager, which refreshes the page according to CSS classes. You are correct that setTimeout is the best way to give up control to the layout manager and see your changes on the screen. You donโ€™t even have to set a delay; a simple call to the setTimeout call allows the layout manager 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'); }); 
+14
source

No need, addClass modifies the DOM directly, so when your for loop starts the wait cursor, it has been added.

Why are you adding a wait cursor for the body tag and all tags?

+1
source

I found another solution: to update the DOM, just scrolling the page for 1 pixel using window.scrollBy(0, 1);

0
source

All Articles