I'd like to add a 1000ms pause between iterations of a for loop. All the solutions I have seen here, of which there are many, simply throw the loop into a function and call that from a setTimeout which just waits then executes the loop at speed. I need it to pause inside the loop. Here's a fiddle.
var button = document.getElementsByTagName('span');
var searchText = 'Activate';
var resultDiv = document.getElementById('results');
for (var i = 0; i < button.length; i++) {
if (button[i].textContent == searchText) {
button[i].click();
var div = document.createElement('div');
div.innerHTML = 'Clicked';
div.className = 'click';
resultDiv.append(div);
// pause before iterating
}
}
2 Answers 2
This might help you.
var button = document.getElementsByTagName("span");
var searchText = "Activate";
var resultDiv = document.getElementById('results');
for (var i = 0; i < button.length; i++) {
(function(j) {
setTimeout(function() {
if (button[j].textContent == searchText) {
button[j].click();
var div = document.createElement("div");
div.innerHTML = 'Clicked';
div.className = 'click';
resultDiv.append(div);
}
}, j * 1000);
})(i);
};
.wrapper {
visibility: hidden;
}
.click {
padding: 5px
}
<div class="wrapper">
<span>Activate</span>
<span></span>
<span></span>
<span>Activate</span>
<span></span>
<span></span>
<span>Activate</span>
<span>Activate</span>
<span></span>
<span>Activate</span>
<span></span>
<span></span>
<span></span>
<span>Activate</span>
<span></span>
<span></span>
<span>Activate</span>
<span></span>
<span>Activate</span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span>Activate</span>
<span></span>
<span></span>
</div>
<div id="results">
</div>
answered Jul 25, 2017 at 5:26
Priya
1,5541 gold badge14 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Kirk Ross
Awesome. I'm trying to refactor it so the delay only happens after the click (when textContent===searchText)... but speeds through the other spans at full speed.
You can use setInterval() like:
setInterval(function () {
if (button[i].textContent == searchText) {
button[i].click();
var div = document.createElement("div");
div.innerHTML = 'Clicked';
div.className = 'click';
resultDiv.append(div);
// pause before iterating
}
if(i==button.length){
clearInterval()
}
i++;
}, 2000);
Comments
lang-js