Best way to iterate over an array without blocking the UI

后端 未结 4 1590
谎友^
谎友^ 2020-11-22 13:10

I am needing to iterate over some large arrays and store them in backbone collections from an API call. What is the best way to do this without making the loop cause the int

4条回答
  •  暖寄归人
    2020-11-22 13:27

    Building on @jfriend00, here is a prototype version:

    if (Array.prototype.forEachAsync == null) {
        Array.prototype.forEachAsync = function forEachAsync(fn, thisArg, maxTimePerChunk, callback) {
            let that = this;
            let args = Array.from(arguments);
    
            let lastArg = args.pop();
    
            if (lastArg instanceof Function) {
                callback = lastArg;
                lastArg = args.pop();
            } else {
                callback = function() {};
            }
            if (Number(lastArg) === lastArg) {
                maxTimePerChunk = lastArg;
                lastArg = args.pop();
            } else {
                maxTimePerChunk = 200;
            }
            if (args.length === 1) {
                thisArg = lastArg;
            } else {
                thisArg = that
            }
    
            let index = 0;
    
            function now() {
                return new Date().getTime();
            }
    
            function doChunk() {
                let startTime = now();
                while (index < that.length && (now() - startTime) <= maxTimePerChunk) {
                    // callback called with args (value, index, array)
                    fn.call(thisArg, that[index], index, that);
                    ++index;
                }
                if (index < that.length) {
                    // set Timeout for async iteration
                    setTimeout(doChunk, 1);
                } else {
                    callback();
                }
            }
    
            doChunk();
        }
    }
    

提交回复
热议问题