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

删除回忆录丶 提交于 2019-11-30 04:13:22

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);
});

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.

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

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

To do this you can set the async property of the ajax request to 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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!