在动画的 for 循环中设置延迟

Set a delay within a for loop for animation

我正在使用 jquery 动画功能来模拟在 CPU 中处理的作业。我正在使用 id = jobj 动态创建 divsj 是每次迭代的作业编号。之后,我将 div 元素分配给一个变量,$process = $(#'job' + j) 用于循环中的每个进程。我想要的是让作业以 1 秒的时间间隔一次一个地进入队列。正在快速连续进入队列,看起来好像只有 3 个基于动画的工作,所以有些地方不对。

这是我目前所掌握的。

// Wait queue
// While jobs are using CPU, other jobs are coming in
for (j = i; j < json_process.length; j++){

    // Check if CPU is being used
    // Processes will be added to the input queue
    // First we check if the queue is empty
    if ( json_process[j].waitTime != 0 ){

        // Convert strings to numbers in the array for calculation and comparison
        completedCPUTime = parseFloat(json_process[i].completedCPUTime); // update CPU time
        joiningInputQueueTime = parseFloat(json_process[j].joiningInputQueueTime); // update joining queue time

        // Send animation[i] to input queue if it has to wait:
        if( completedCPUTime > joiningInputQueueTime && waitIndex < j){

            // Create job Div element
            elm = '<div id="job' + j + '" ' +
                    'style="background-color:red; width:5px; height:50px; position:absolute; margin-top:30px;" >' +
                    ' </div>';
            $(elm).appendTo('#animate');


                // Get process div
                var $process = $('#job' + j);
                var pos = process.offset().left; // position of process
                // The end of the queue
                var queueEnd = queue.offset().left + queue.outerWidth() - process.outerWidth();


            input_queue.push(j); // push job in input queue
            alljobs.push(j);


                    // Animate Div element $process
            // Pausing loop on each job going into queue
            setTimeout(function() {
                // Send Job joiningInputQueueTime[j] to queue div
                $process.stop().animate(
                    {left: queueEnd},
                    {duration: 1000});
            }, 5000);

            //This will keep track of the last index waiting
            waitIndexCurrent = j;

        }// End of animation condition
    }// End of wait condition
} // End of wait queue time For Loop

延迟内部循环刺激是不可能的,但你可以像这样递归地做一些事情(根据需要改变刺激的数量、延迟和起始值:

(function theLoop (j) {
      setTimeout(function () {
             //your code here
            if (j++ < number of irritations) {          
             theLoop(j);       
        }
      }, delay in miliseconds);
})(starting value);