我想在用户单击我的按钮时执行简单的代码:
- 第一:将光标更改为“等待”
- 下一步:执行循环
- 循环完成后:将光标更改回“默认”
我写了这段代码:
HTML:
<button type="button" id="gogogo">Go!</button>
<div id="progress">0</div>
JS:
var progress = document.getElementById('progress');
document.getElementById('gogogo').onclick = (function(){
document.body.style.cursor = 'wait';
for(var ii = 0; ii < 30000; ii += 1){
progress.textContent = ii;
}
document.body.style.cursor = 'default';
});
实时代码在这里:http://jsfiddle.net/4Bz27/2/
有什么地方不对劲。首先循环执行,然后发生光标变化。
是否可能或以任何方式与异步相关?
您正在执行阻塞操作。这肯定会在某些时候导致缓慢的脚本警告。您可以通过使循环异步来解决此问题:
var progress = document.getElementById('progress');
document.getElementById('gogogo').onclick = (function(){
document.body.style.cursor = 'wait';
var index = 0,
updater;
updater = function() {
progress.textContent = index++;
if (index < 30000) {
setTimeout(updater, 50);
} else {
document.body.style.cursor = 'default';
}
};
updater();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)