1

I'm a beginner to coding and I've been trying to delay a button click function using timeout but it seems like not working.

To clarify it further, this button is supposed to do something, but when I add timeout function all it does is just delay it and not processing to the next line. Even with JavaScript is okay. Can anyone help me out. Thanks in advance. :)

$(document).ready(function () {
 setTimeout(function(){
 $("#mybutton").click(myButtonClicked);
 }, 1000);
 getURLParameter("run") && $("#mybutton").click()
});


function getURLParameter(a) {
 a = (new RegExp("[?|&]" + a + "=([^&;]+?)(&|#|;|$)")).exec(location.search);
 if (null == a) return null;
 a = a[1];
 a = a.replace(/\+/g, "%20");
 return decodeURIComponent(a)
}

function myButtonClicked() {
 disableMyButton();
 var a = $(".new").toArray(),
  c = $(".status").toArray();
 a.reverse();
 c.reverse();
 doNextBox(a, c)
}

What I'm trying to do is

  1. Click button
  2. Wait a second
  3. Proceed to the next task
Berglund
  • 636
  • 2
  • 7
  • 20
  • 2
    Where is your code of delay ? – Sagar Agrawal Oct 01 '19 at 22:28
  • Sorry, I just updated it now. – Berglund Oct 01 '19 at 22:33
  • 1
    @RashmiNimesha we'll need acreate a **[minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)** to help you. However, you can check `.delay()` method on the **[jQuery API Documentation](https://api.jquery.com/delay/)** – Manuel Abascal Oct 01 '19 at 22:36
  • 3
    You need to wrap the other line in the `setTimeout`. `$("#mybutton").click(myButtonClicked);` installs the event listener (which you can and should do immediately), `$("#mybutton").click()` fires the click (which you want to do later, in the timeout callback). – Bergi Oct 01 '19 at 22:39
  • 2
    Your code basically adds listener to click event after 1s, but you click it immediately. To make it work, you should switch .click methods. – bigless Oct 01 '19 at 22:40
  • Possible duplicate of [How do I delay a function call for 5 seconds?](https://stackoverflow.com/questions/4738595/how-do-i-delay-a-function-call-for-5-seconds) – marcdecline Oct 01 '19 at 22:42
  • It's not. I've already tried it. :/ – Berglund Oct 01 '19 at 22:44

1 Answers1

5

Call setTimeout in your 'click'-eventhandler, pass a function and the time after that this function should be executed...

Example:

$('#mybutton').click(function() {
   setTimeout(doAfterTimeout, 1000);
});

function doAfterTimeout() {
  console.log('test');
}