I want to program a delay in the .click(function() {...}) handler before the function is executed. This doesn't work:
$('.okButton').click(setTimeout(function() { ...}, 3000))
It gives this error (in Chrome):
Uncaught TypeError: Object 2 has no method 'apply'
The JQuery docs don't give any clue as to why this doesn't work.
How can I put a delay before executing the function handler?
I want to program a delay in the .click(function() {...}) handler before the function is executed. This doesn't work:
$('.okButton').click(setTimeout(function() { ...}, 3000))
It gives this error (in Chrome):
Uncaught TypeError: Object 2 has no method 'apply'
The JQuery docs don't give any clue as to why this doesn't work.
How can I put a delay before executing the function handler?
Share Improve this question asked Sep 23, 2013 at 20:49 Dean SchulzeDean Schulze 10.3k25 gold badges116 silver badges180 bronze badges4 Answers
Reset to default 8It doesn't work because setTimeout()
doesn't return a function; it returns a timer handle (a number).
This should work:
$('.okButton').click(function() { setTimeout(function() { ...}, 3000); });
The argument expressions in JavaScript function calls are always fully evaluated before the function is called. Your code called setTimeout()
, and the return value from that was passed into the jQuery routine.
The solution is to have a .click() handler function that just calls setTimeout() with a handle to the real handler function:
$('.okButton').click(function() {
setTimeout(okButtonClickHandler, 3000)
});
When I tried this before it called the handler function immediately because I include parenthesis on the argument to setTimeout().
Don't do this:
$('.okButton').click(function() {
setTimeout(okButtonClickHandler(), 3000)
});
It will execute the handler function immediately.
Why don't you put the timeout inside the callback?
$('.okButton').click(function() {
setTimeout(function(){
alert("Hello");
},3000);
});
You can do something like:
$(".okbutton").click(function(event) {
var timeout = setTimeout(function() {
alert("Foo");
}, 3000)
});
You can try out the working example. After clicking the word click it takes three seconds for the alert to appear.