Loop is more important than rest?

后端 未结 4 1721
旧巷少年郎
旧巷少年郎 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 07:50

    Your Loop is happening too fast for any result to be shown.

    Everything is done but in about < 1ms. You could use timeouts to delay what's being shown so that you can see what's happening.

    Edit: here is the JsFiddle Link: http://jsfiddle.net/4Bz27/9/

    var progress = document.getElementById('progress');
    
    var restoreCursor= function () {
       document.body.style.cursor = 'default';
     }
    
    document.getElementById('gogogo').onclick = (function(){
        document.body.style.cursor = 'wait';
    
        var ii = 0;
        // this is a immediately executed function
        //that calls itself with a small timeout  
        (function goLoop(){
    
            progress.textContent = ii;
    
            if(ii<30000){
               ii++;
               setTimeout(goLoop,10);
            }else {
              restoreCursor();
            }
    
        })();
    
    
    
    });
    

    replace your jsFiddle by that and you're good to go.

    personnally for better performance i would iterate over each frame. like this:

    var ii =0;
    (function goLoop(){
      progress.textContent = ii;
      if(ii>3000) {
        ii++;
        requestAnimationFrame(goLoop);
    })();
    

提交回复
热议问题