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
}
}
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>
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.