Applying a delay between each iteration of the jQuery.each () method

Having some problems with the following code block:

$('.merge').each(function(index) { var mergeEl = $(this); setTimeout(function() { self.mergeOne(mergeEl, self, index - (length - 1)); }, 500); }); 

I am trying to apply a .500 second delay between each call to mergeOne , but this code only applies a 0.5 second delay before calling mergeOne for all elements of the array at the same time.

If someone can explain why this code is not working and maybe a working solution that would be awesome, thanks!

+6
source share
1 answer

Here is a generic function that you can use to iterate through a collection of jQuery objects with a delay between each iteration:

 function delayedEach($els, timeout, callback, continuous) { var iterator; iterator = function (index) { var cur; if (index >= $els.length) { if (!continuous) { return; } index = 0; } cur = $els[index]; callback.call(cur, index, cur); setTimeout(function () { iterator(++index); }, timeout); }; iterator(0); } 

DEMO: http://jsfiddle.net/7Ra9K/ (loop once)

DEMO: http://jsfiddle.net/42tXp/ (continuous loop)

The context and arguments passed to your callback should be the same as .each() .

If you want to make it a jQuery plugin, you can call it $("selector").delayedEach(5000, func... , then you can use this:

 $.fn.delayedEach = function (timeout, callback, continuous) { var $els, iterator; $els = this; iterator = function (index) { var cur; if (index >= $els.length) { if (!continuous) { return; } index = 0; } cur = $els[index]; callback.call(cur, index, cur); setTimeout(function () { iterator(++index); }, timeout); }; iterator(0); }; 

DEMO: http://jsfiddle.net/VGH25/ (loop once)

DEMO: http://jsfiddle.net/NYdp7/ (continuous loop)


UPDATE

I added the possibility of a continuous loop of elements, as an additional parameter. Passing true will be a continuous loop, and passing false or nothing (or something false) will only cycle through the elements once. Code and scripts include changes.

+7
source

Source: https://habr.com/ru/post/951469/


All Articles