且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在jQuery.each函数的每个循环之间进行延迟?

更新时间:2022-01-06 03:53:49

增加时间的setTimeout:

setTimeout at an increase time:

$('li').each(function(indexInArray){
   var data = $(this).text();
   setTimeout( function () {
       requestFunction(data, function(status){
           if ( status == 'OK' ) do stuff...
       });
   }, indexInArray * 500);
});






如果你循环遍历这些元素,我们想要增加超时,否则所有请求都会在没有延迟的情况下同时触发,但仅在我们的500毫秒超时后才会触发。


if you loop over these elements, we want to increase the timeout or else all the request would fire at the same time if not delayed, but only after our 500 ms timeout.


  • 时间开始: 0 ms

  • 第一次请求: 0 ms(500 * 0)

  • 秒要求: 500毫秒(500 * 1)

  • 第三次请求: 1000毫秒(500 * 2)

  • Time Start: 0 ms
  • First Request: 0 ms (500 * 0)
  • Second Request: 500 ms (500 * 1)
  • Third Request: 1000 ms (500 * 2)