循环比休息重要吗? [英] Loop is more important than rest?

查看:92
本文介绍了循环比休息重要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户单击我的按钮时,我想执行简单的代码:

I want to execute simple code when user click on my button:

  1. 首先:将光标更改为等待"
  2. 下一步:执行循环
  3. 循环结束后:将光标更改回默认"

我写了这段代码:

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/

出了点问题.循环先执行,然后再进行游标更改. 是否可能或与异步相关的任何方式?

And something is wrong. Loop execute first, and after that happen cursor changing. Is it possible or any way related to asynchronous?

推荐答案

RequestAnimationFrame方法

RequestAnimationFrame Way

jsFiddle此处

(function (W) {
    W.onload = function () {
        var D = W.document,
            a = 0,
            c = D.getElementById('progress');

        function b() {
            c.innerText = a + 1;
            a++;
            if (a < 500) {
                requestAnimationFrame(b);
            } else {
                D.body.style.cursor = 'default';
            }
        }

        function start() {
            D.body.style.cursor = 'wait';
            b()
        }
        D.getElementById('gogogo').onclick = start;
    }
})(window)

这样,您可以使用更少的资源,因此复杂的链接修改不会降低其他打开的网站的速度.

This way you use less resources and so your complex link modification does not slow down other open websites.

这篇关于循环比休息重要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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