How can I add a setTimeOut to avoid script unresponsiveness inside a each loop?, basically there is this grid where I have many rows, and the rows have a column that consists of a kendo datepicker. The problem is that after a few a bound to the grid i get the unresponsive script box, then i have to click continue and it would work:

var j = 0;

$$('.dtInputs'),each(function (input){

    j++;
    input.kendoDatePicker();
    if(j > 500){
       if(j % 1000 = 0)
       {
           window.setTimeOut(arguments.callee, 1);
           return false;
       }
    }
});

The problem is that by looking at this i dont think it will continue adding the datepicker after it returns false to the remaining inputs. Not sure how to do this.

有帮助吗?

解决方案

The problem here is that the .each itself is synchronous.

  • You can off-load your script to webworkers
  • Or make an async loop yourself using setInterval

In your case, this should work

$.fn.asyncEach = function(callback){
  var i = 0;
  var elements = this;
  var timer = setInterval(function(){
    callback.call(elements[i],elements[i]);
    if(++i >= elements.length) clearInterval(timer);
  },0);
}

$('.dtInputs').asyncEach(function(){
  $(this).kendoDatePicker();
});

Note that I'm using timers to force asynchronous behavior. It will prevent blocking the UI, but will be significantly slower in processing.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top