How to set a setTimeOut to avoid script unresponsive inside .each loop

1.2k views Asked by At

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.

1

There are 1 answers

1
Joseph On BEST ANSWER

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.