-2

I have some loop like below..which clicks all buttons

for(var i = 1;i<document.querySelectorAll(".myclass").length;i++){

document.querySelectorAll(".myclass")[i].click();
console.log("hi");

}; 

but I want to add sleep function that delays each loop like sleep(2000); , Is there any function in javascript like that ?

I tried below code , but does not work

for(var i = 1;i<document.querySelectorAll(".myclass").length;i++){


setTimeout(function() {

document.querySelectorAll(".myclass")[i].click();
console.log("hi");

}, (3 * 1000));




}; 
Vishnu
  • 2,372
  • 6
  • 36
  • 58
  • 2
    Possible duplicate of [Sleep in Javascript - delay between actions](http://stackoverflow.com/questions/758688/sleep-in-javascript-delay-between-actions) – JDurstberger Nov 24 '15 at 09:52
  • you cant directly set a timeout for the iteration itself, but you can call a timeout within each iteration – Alex Nov 24 '15 at 09:56
  • stop down voting..I just placed setinterval inside , but it doesnt run the loop – Vishnu Nov 24 '15 at 09:57
  • The `setTimeout` executes the click 3 seconds later, but since the loop continues without stopping, it will click ALL links 3 seconds later, all at once. – Ivar Nov 24 '15 at 10:05
  • yea I so what will be the correct way to delay clicks between each loops?? – Vishnu Nov 24 '15 at 10:06
  • Note that Javascript works asynchronously, so there is not really a sleep method. You should take a look at callbacks. That way, you can synchronize the clicks. – Ivar Nov 24 '15 at 10:08
  • An other way is to use an `setInterval()`, and use a custom counter. – Ivar Nov 24 '15 at 10:09
  • can you tell me correct steps ? so I must use setInterval inside function and call another function outside>? – Vishnu Nov 24 '15 at 10:11

2 Answers2

1

Create the new function as give and call that function inside your loop.

function sleep(milliseconds) {
    var start = new Date().getTime();
    while ((new Date().getTime() - start) < milliseconds) {

    }
}

for (i = 0; i < 3; i++) {
    console.log(i);
    sleep(5000);
}
Mitul
  • 3,431
  • 2
  • 22
  • 35
1

var myVar = setInterval(myTimer, 2000);
var divIndex = 0;
function myTimer() {
    if(divIndex < document.querySelectorAll(".myclass").length){
      document.querySelectorAll(".myclass")[divIndex].click();  
       console.log(divIndex); 
    }else {
     clearInterval(myVar);
    }
    divIndex++;
}
<div class='myclass'></div>
<div class='myclass'></div>
<div class='myclass'></div>
<div class='myclass'></div>
Mitul
  • 3,431
  • 2
  • 22
  • 35