JavaScript中的DoEvents [英] DoEvents in JavaScript

查看:148
本文介绍了JavaScript中的DoEvents的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

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

但是我不确定cursor:wait图标是否立即显示.

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

问:有没有办法用JavaScript来说"DoEvents",这样我就知道DOM在进入循环之前正在被更新?

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?

也许使用setTimeout方法.

Maybe using the setTimeout method.

推荐答案

正在发生的事情:

处理您的页面的浏览器实例是单线程的. DOM更改立即发生.但是,当您的脚本运行时,浏览器被阻止并且无法运行其布局管理器,该布局管理器根据CSS类的更改来更新页面.您是正确的,setTimeout是将控制权让给布局管理器并在屏幕上查看所做更改的最佳方法.您甚至都不需要设置延迟,调用setTimeout的简单操作使布局管理器有机会重绘页面.

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');
});

这篇关于JavaScript中的DoEvents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆