user11476228
user11476228

Reputation:

Auto-click again after 3 seconds after click

Auto-click again after 3 seconds after click. Why don't work?

$(document).on("click", "input[name='submit']", setTimeout(function(){
      $(this).trigger('click');
}, 3000));

Upvotes: 0

Views: 3875

Answers (2)

Mohammad
Mohammad

Reputation: 21489

You need to detect which click event is manual and which is automatically. So define timer variable to do this work. If timer equal to false that mean click is manual and if be true mean is automatically.

Note that when setTimeout callback is called the this refer to window, so you need to store this is variable (ele)

var timer = false;
$(document).on("click", "input[name='submit']", function(e){
  var ele = this;
  // First click
  if (!timer){
    e.preventDefault();
    $(ele).prop("disabled", true)
    setTimeout(function(){
      timer = true;
      $(ele).prop("disabled", false).trigger('click');
    }, 3000)
  // Second click
  } else {
    console.log("Submit form");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="submit" name="submit" value="click">

Upvotes: 1

rlemon
rlemon

Reputation: 17666

I see two problems with your code:

First, your are putting your setTimeout in for your callback. setTimeout returns an int id for the timer it spawns. So essentially what you have now is:

.on('click', selector, 123);

which obviously won't work.
If you want your code to execute later on, put the setTimeout inside of the callback.

.on('click', selector, function() {
  setTimeout(myFunc, 3000);
});

then your callback runs on click, and spawns the timer.

Secondly, I assume you want this inside of the callback to refer to the clicked object, and not window.. so you'll have to pass a thisArg to setTimeout or define it in the parent scope.. or use arrow functions which don't bind a new thisArg. For simplicity I suggest using arrow functions.

setTimeout( () => {
  $(this).trigger('click');
}, 3000);

Upvotes: 2

Related Questions