1

I have this code that clicks all buttons once.. what i want is to have a small delay 1 second after each button is clicked.. so not really at once, but simultaneously one after the other.... till all buttons are clicked!

here's the code:

var inputs = document.getElementsByClassName('xxxxxxxx'); 

for (var i=0; i<inputs.length;i++) 
{ 
    inputs[i].click(); 
}
JoeDoow
  • 11
  • 1

3 Answers3

1

Use setTimeout()

Add set timeout on the third line of your code as shown below to click on every one second. Also, use let instead of var to make it work:

var inputs = document.getElementsByClassName('xxxxxxxx'); 

for (let i=0; i<inputs.length;i++) // Use let not var to declare i
{ 
    setTimeout(inputs[i].click, i*1000);  // <<<<<< Here
}
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
1

Assuming ES6 is allowed you can one line this with map:

const inputs = document.getElementsByClassName('xxx');
const clickButton = (btn) => btn.value = 'Clicked'

Array.from(inputs).map((x, i) => setTimeout(() => clickButton(x), i * 2000))
<input type="submit" class="xxx" onclick="log()" />
<input type="submit" class="xxx" onclick="log()" />
<input type="submit" class="xxx" onclick="log()" />
Akrion
  • 18,117
  • 1
  • 34
  • 54
0

You could use recursion, instead of a for loop, and include a timeout in your function. Example:

const inputs = document.getElementsByClassName('button'); 

const logClicked = () => console.log('clicked')

const checkTheBox = (arr,pos) => {
  if (pos < arr.length) {
    arr[pos].click()
    arr[pos].style.background = 'red'
    setTimeout(() => checkTheBox(arr, pos+1), 1000)
  }
  return
}

checkTheBox(inputs, 0)
.button {
  border:1px solid black;
  background: white;
}
<div class="wrapper">
  <input type="submit" class="button" onclick="logClicked()" />
  <input type="submit" class="button" onclick="logClicked()"/>
  <input type="submit" class="button" onclick="logClicked()"/>
  <input type="submit" class="button" onclick="logClicked()"/>
  <input type="submit" class="button" onclick="logClicked()"/>
  <input type="submit" class="button" onclick="logClicked()"/>
  <input type="submit" class="button" onclick="logClicked()"/>
</div>
FranCarstens
  • 1,203
  • 8
  • 13