-1

I'm simulating the process of clicking all buttons in a page and now I would like to have some delay between each click by using the following code, but for some reason it refuses to work and no button is clicked:

var time = 500;
$("button").each(function() {
  setTimeout(function() {
    $(this).click();
  }, time);
  time += 500;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <title>TEST</title>
</head>

<body>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
</body>

</html>

Any ideas?

Yair Nevet
  • 12,046
  • 12
  • 61
  • 101

2 Answers2

0

var time = 500;
$("button").each(function() {
  setTimeout(function() {
    $(this).click();
  }.bind(this), time);
  time += 500;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <title>TEST</title>
</head>

<body>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
  <button type="button">Click Me!</button>
</body>

</html>
Kevin Jantzer
  • 8,404
  • 2
  • 24
  • 49
0

I'm not entirely sure what you want to achieve, because your code doesn't do a whole lot... all I can imagine is that you want to do something when a button is pressed with an increased time after each press... if so, here you go:

var time = 500;

$(document).ready(function() {
  $('button').click(function() {
    $(this).delay(time).queue(function(n) {
      $(this).text("I've been clicked!");
      time += 500;
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
TheThirdMan
  • 1,435
  • 12
  • 25