How can I give control back (briefly) to the browser during intensive JavaScript processing?

后端 未结 4 640
孤城傲影
孤城傲影 2020-11-27 03:15

I have read the post here about using setTimeout() during intensive DOM processing (using JavaScript), but how can I integrate this function with the below code? The below c

4条回答
  •  情深已故
    2020-11-27 03:39

    It just so happens that I was posting about this a moment ago here. Here is a timed loop function:

    function processLoop( actionFunc, numTimes, doneFunc ) {
      var i = 0;
      var f = function () {
        if (i < numTimes) {
          actionFunc( i++ );  // closure on i
          setTimeout( f, 10 )
        } 
        else if (doneFunc) { 
          doneFunc();
        }
      };
      f();
    }
    

    For your situation this would be used like this:

    function appendToSelect () {
    
      $("#mySelect").children().remove() ;
      $("#mySelect").html(
          ''
      );
      var j = 1 ;
    
      processLoop(function (i){
        $("#mySelect").append(
            ''
        ); 
      }, obj.data.length);
    
    }
    

    You'll want to make sure that you have a closure or some other access to the obj variable within the iteration function.

    Hope this helps.

提交回复
热议问题