Search code examples
javascriptdelay

How to sleep in for loop


How do I make a 5 second delay in following code before moving to the next input element:

var inputs = document.getElementsByClassName('_aj7');
for(var i = 0; i < inputs.length; i++) {
    inputs[i].click();
}

Solution

  • If you want to introduce a delay between actions, you need to use something like setTimeout. For example:

    function f() {
      inputs[i].click();
      if (++i < inputs.length) {
        setTimeout(f, 5000);
      }
    }
    
    var inputs = document.getElementsByClassName('_aj7');
    var i = 0;
    if (i < inputs.length) {
      f();
    }