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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7445941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:09:51  来源:igfitidea点击:

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

javascriptjquerydelayeach

提问by Ax.

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()". How could i do this? Hope it understandable, thanks.

所以,我需要在使用函数“requestFunction()”之间做一些延迟。我怎么能这样做?希望可以理解,谢谢。

回答by Joe

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
  • First Request: 0 ms (500 * 0)
  • Second Request: 500 ms (500 * 1)
  • Third Request: 1000 ms (500 * 2)
  • 时间开始:0 毫秒
  • 第一个请求:0 毫秒(500 * 0)
  • 第二个请求:500 毫秒(500 * 1)
  • 第三次请求:1000 毫秒(500 * 2)

回答by Jamie Dixon

If you're making ajax calls within your eachloop then you may want to run the ajax requests syncronously.

如果您在each循环中进行 ajax 调用,那么您可能希望同步运行 ajax 请求。

To do this you can set the asyncproperty of the ajax request to false.

为此,您可以将asyncajax 请求的属性设置为false.

Alternatively you may want to look into implimenting a callback for requestFunction. This will allow you to run code after your method has returned and will negate the need for any timeout etc.

或者,您可能想研究为requestFunction. 这将允许您在方法返回后运行代码,并且不需要任何超时等。

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.

回调基本上是在代码末尾执行的方法。你基本上告诉你的函数,这是我希望你在完成工作后调用的另一个函数。