-3

I get 5 button, each click will trigger event to generate new different button real time. Question is how to simulate each button click event over 2 seconds. Like other language, use

thread.sleep(2000); //will delay 2 sec

In javascript, here is some direction Arguments.callee is deprecated - what should be used instead?

setTimeout(function () { ... setTimeout(arguments.callee, 100); }, 100); and another direction is delay() function in jquery

But can it trigger generate button event?

$(document).ready(function() {
  timer();
});

function timer() {
  setTimeout(function() {

    setTimeout(arguments.callee, 2000);
  }, 2000);

};

function addBtn(btn) {
  $("#p2").text(btn.value) // btn.value;
  var count = Math.round((Math.random() * 2 * 1000) / 1000, 0) + 1;
  console.log(count);
  $(".addbtn").remove();
  for (i = 0; i < count; i++) {
    $("#d2").append("<input class='addbtn' type='button' style='width:100px;color:green' value='subBtn" + btn.value + "_" + (i + 1) + "'/>")
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d1">
  <input id="btn1" type="button" onclick="addBtn(this)" style="width:100px;color:green" value="1" />
  <input id="btn2" type="button" onclick="addBtn(this)" style="width:100px;color:green" value="2" />
  <input id="btn3" type="button" onclick="addBtn(this)" style="width:100px;color:green" value="3" />
</div>
<div id="d2">

</div>
Community
  • 1
  • 1
Max CHien
  • 133
  • 1
  • 8

1 Answers1

0

If you have five buttons and want to click them each in order, clicking one every two seconds, you'd use $() to look them up, then yes, you'd use setTimeout to schedule the clicks.

You haven't shown any markup or code, but for example, this clicks each of the five buttons with a two-second delay between clicks (no initial delay):

// Look up the buttons
var btns = $("input[type=button]");

// Something so we can see them get clicked
btns.on("click", function() {
  $("<p>").text("Button " + this.value + " clicked").appendTo(document.body);
});

// Loop through them, scheduling a click on each one after 2000ms
// (two seconds). Note how we're multiplying 2000 by the index
// of the button -- the first button is index 0, so that's 0ms
// (almost immediate), the second is index 1 = 2000ms from now,
// the third is index 2 = 4000ms from now...
btns.each(function(index) {
  var $btn = $(this);
  setTimeout(function() {
    $btn.click();
  }, 2000 * index);
});
<input type="button" value="One">
<input type="button" value="Two">
<input type="button" value="Three">
<input type="button" value="Four">
<input type="button" value="Five">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

That's just one of several different ways to do it.

lshettyl
  • 8,166
  • 4
  • 25
  • 31
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875