When I implemented the timeChunk function, I found that the logic code went one more time. But I don't know why.

the code is as follows:

var timeChunk = function(data, fn, count, time) {
    var that = this,
        obj,
        index = 0,
        timer;
    var start = function() {
        index += 1;
        for (var i = 0; i < Math.min(count || 1, (data.length + 1)); iPP) {
            console.log("start:" + index + ",i:" + i + ", data:" +
                (data.length + 1))
            console.log(Math.min(count || 1, (data.length + 1)))
            obj = data.shift();
            fn(obj);
        }
    }
    return function() {
        timer = setInterval(function() {
            if (data.length === 0) return clearInterval(timer);
            start();
        }, count)
    }

}

var arr = [
    "nice to meet you",
    "hello",
    "xixi",
    "nice to meet you",
    "hello",
    "xixi"
];

var getMsgToDo = function(obj) {
    var div = document.createElement("div");
    div.innerHTML = obj;
    document.body.appendChild(div);
}

var renderList = timeChunk(arr, getMsgToDo, 3, 200);

renderList()

in the end, the start executed three times. I passed in three pieces of data and six pieces of data should be executed twice.

after troubleshooting, start exited the loop the second time it was executed, but I don"t know why.
Mar.13,2021

when start executes the second time and loops to iTunes 2, it is the fifth cycle, and this cycle is judged to be

.
i < Math.min(count || 1, (data.length + 1))

there is only one piece of data left in the data.length at this time, so I is not less than 2 and exits the loop. But the timer hasn't been cleaned yet, so after the 3ms, the loop from iTun0 restarts, which proves that the last segment of the console output is: the number of start is 3.
finally, in my humble opinion, the determination of the loop should be changed to

.
i < count

that is, change the core code of the loop to

for (var i = 0; i < count; iPP) {
    console.log('start:' + index + ',i:' + i + ', data:' +data.length)
    obj = data.shift();
    fn(obj);
}

finally, I attach my modified console output. I don't know if it is what you want it to look like:

start:1,i:0, data:6
start:1,i:1, data:5
start:1,i:2, data:4
start:2,i:0, data:3
start:2,i:1, data:2
start:2,i:2, data:1

it's late at night and I'm not very clear-headed. I hope my opinion can help you

Menu