简体   繁体   English

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

[英]How to make delay between each loops of jQuery.each function?

I have this-like code: 我有这样的代码:

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

So, i need to do some delay between using function "requestFunction()". 所以,我需要在使用函数“requestFunction()”之间做一些延迟。 How could i do this? 我怎么能这样做? Hope it understandable, thanks. 希望它可以理解,谢谢。

setTimeout at an increase time: setTimeout在增加的时间:

$('li').each(function(indexInArray){
   var data = $(this).text();
   setTimeout( function () {
       requestFunction(data, function(status){
           if ( status == 'OK' ) do stuff...
       });
   }, indexInArray * 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. 如果你遍历这些元素,我们想要增加超时,否则如果没有延迟,所有请求都会同时触发,但仅在我们500毫秒超时之后。

  • Time Start: 0 ms 时间开始: 0毫秒
  • First Request: 0 ms (500 * 0) 第一次请求: 0 ms(500 * 0)
  • Second Request: 500 ms (500 * 1) 第二次请求: 500毫秒(500 * 1)
  • Third Request: 1000 ms (500 * 2) 第三次请求: 1000毫秒(500 * 2)

If you're making ajax calls within your each loop then you may want to run the ajax requests syncronously. 如果您在each循环中进行ajax调用,那么您可能希望同步运行ajax请求。

To do this you can set the async property of the ajax request to false . 为此,您可以将ajax请求的async属性设置为false

Alternatively you may want to look into implimenting a callback for requestFunction . 或者,您可能希望查看对requestFunction的回调。 This will allow you to run code after your method has returned and will negate the need for any timeout etc. 这将允许您在方法返回后运行代码,并将取消任何超时等的需要。

A callback is basically a method that gets executed at the end of your code. 回调基本上是一种在代码末尾执行的方法。 You basically tell your function, here's another function I want you to call when you've finished doing your work. 你基本上告诉你的功能,这是我希望你在完成工作后打电话的另一个功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM