Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 464
Ax. Avatar asked Sep 16 '11 14:09

Ax.


People also ask

What is the use of delay () method in jQuery?

The delay() method sets a timer to delay the execution of the next item in the queue.

Is delay event method in jQuery?

Added to jQuery in version 1.4, the . delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .

Which loop is faster in jQuery?

jQuery each() vs for loopThe 'FOR' loop being a native Javascript function is undoubtedly faster, however the scope is all the same, so in some cases the . each() method would be preferable, as each iteration is its own scope.


2 Answers

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)
like image 109
Joe Avatar answered Oct 26 '22 22:10

Joe


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.

like image 31
Jamie Dixon Avatar answered Oct 26 '22 23:10

Jamie Dixon