Loop is more important than rest?

后端 未结 4 1724
旧巷少年郎
旧巷少年郎 2021-01-14 07:12

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

  1. First: change my cursor to \'wait\'
  2. Next: execute loop
  3. When loop is finished: cha
4条回答
  •  执念已碎
    2021-01-14 08:10

    You are performing a blocking operation. This will certainly cause slow script warnings at some point. You can solve this by making the loop asynchronous:

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

提交回复
热议问题