Restart Jquery.each() After Loop Ends
Solution 1:
There are two issues with trying to restart a .each()
loop this way. First and foremost, that's not how .each()
really works. It's less a loop and more shorthand for calling the function on every element. If you gave that anonymous function a name (let's go with setPlaceholder()
), the .each()
call is essentially doing this:
setPlaceholder(0, arr[0]);
setPlaceholder(1, arr[1]);
setPlaceholder(2, arr[2]);
setPlaceholder(3, arr[3]);
setPlaceholder(4, arr[4]);
setPlaceholder(5, arr[5]);
The index value it passes to the function isn't used for looping purposes, so trying to set it to 0 won't have any impact on the .each()
call.
The second issue is your if condition. It'll never actually fire, since the final "iteration" of the .each()
call will have arr.length - 1
as its value, not arr.length
.
I'm not sure why you want to have it keep looping, but if that's your goal, you could accomplish it like this:
functioneachChange(){
$.each(arr, function (index, value) {
setTimeout(function() {
$('input').attr('placeholder', value);
}, index * 1000);
if (index == arr.length - 1) {
setTimeout(eachChange, (index + 1) * 1000);
}
});
}
eachChange();//call function
What that should do is schedule eachChange()
to be called again 1 second after the last placeholder update takes place. You can add in some other checks to limit the number of times it recurses, but if you want it to happen indefinitely that should do the trick.
Solution 2:
you can compare the index with the arr.length like this
var arr = newArray();
for (var i = 0; i <= 5; i++) {
arr.push('Value ' + i);//fill array with values
}
functioneachChange(){
$.each(arr, function (index, value) {
setTimeout(function(){
$('input').attr('placeholder', value);
//if it is the last element in arr setTimeout and call eachChange() if(index>=arr.length-1){
setTimeout(function(){
eachChange();
},1000);
}
}, index * 1000);
});
}
eachChange();
Solution 3:
I dont think you can reset the counter of the $.each function, as it seems to encapsulate a simple for loop. You dont have access to the counter from the outside.
However, try:
functioneachChange(initX){
var x = initX || 0;
$.each(arr, function (index, value) {
x++;
setTimeout(function(){
$('input').attr('placeholder', value);
}, x * 1000);
// Call yourself but pass current xif(index==arr.length) eachChange(x);
});
}
Remove the initX part if you want x to reset, but i assume you want it to keep counting from where the previous loop finished.
Post a Comment for "Restart Jquery.each() After Loop Ends"