Reputation: 302
I am executing this JavaScript which is kind of self explanatory (I think). There are around 100 buttons on a page with class button
and I want them to click one by one. It's working fine.
But I want to add a delay of 5 seconds before this clicks next button.
var mybtn = document.getElementsByClassName('.button');
for( var i=0; i<100; i++ ) {
mybtn[i].click();
}
Upvotes: 2
Views: 5701
Reputation: 30098
If you don't mind using another library to solve this problem, then I suggest you use Kristopher Michael Kowal's Q library. Using promises by using Array.prototype.reduce, to iterate and resolve promises when they need to be fulfilled.
// Query all buttons
var buttons = document.querySelectorAll('.button');
// Register Click Event Handlers
Array.prototype.forEach.call(buttons, registerButtonClickHandlers);
// Invoke button click
Array.prototype.reduce.call(
buttons,
reduceButtonPromises ,
Q.when()
);
function registerButtonClickHandlers(button) {
button.addEventListener('click', function() {
// display time end
console.timeEnd(button.innerHTML);
});
}
function reduceButtonPromises(promise, button) {
// register promise callback
return promise.then(function() {
// deferred object
var deferred = Q.defer();
setTimeout(function() {
// set time start
console.time(button.innerHTML);
// click button
button.click();
// resolve the promsie to trigger the next promise
deferred.resolve();
}, 100);
// promise
return deferred.promise;
});
}
Upvotes: 0
Reputation: 18566
You can use setInterval
for that functionality.
Instead of manually specifying 100
use the length property.
Also avoid using getElementsByClassName
its not standard. Instead document.querySelectorAll
is supported by most of the browsers.
var mybtn = document.querySelectorAll('.button');
var i = 0;
var timer = setInterval(function() {
if( i < mybtn.length) {
mybtn[i].click();
console.log("Click handler for button " + i + " fired");
} else {
clearInterval(timer);
}
i = i + 1;
}, 5000);
<div class="button">Hi1</div>
<div class="button">Hi2</div>
<div class="button">Hi3</div>
<div class="button">Hi4</div>
<div class="button">Hi5</div>
Upvotes: 6
Reputation: 4951
Something like this?
//var buttons = document.getElementsByClassName('.button'); // Not standard
var buttons = document.querySelectorAll('.button');
function clickButton(index) {
mybtn[index].click();
if(index < buttons.length) {
setTimeout("clickButton(" + (index+1) + ");", 5000);
}
}
setTimeout("clickButton(0);", 5000);
For testing, I added alert()
:
//var buttons = document.querySelectorAll('.button');
function clickButton(index) {
//mybtn[index].click();
alert("button" + index);
if(index < 100) {
setTimeout("clickButton(" + (index+1) + ");", 5000);
}
}
setTimeout("clickButton(0);", 5000);
Upvotes: 2
Reputation: 1831
You can use the setTimeout function to call the click function every 5 seconds.
Something like:
setTimeout(function(){ mybtn[i].click(); }, 5000);
Upvotes: 1