1

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.

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
 }
}
Priya
1,5541 gold badge14 silver badges33 bronze badges
asked Jul 25, 2017 at 5:21

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

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);
answered Jul 25, 2017 at 5:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.