Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .click() handler can't accept setTimeout() around the function

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?

like image 911
Dean Schulze Avatar asked Oct 25 '25 01:10

Dean Schulze


1 Answers

It 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.

like image 71
Pointy Avatar answered Oct 26 '25 14:10

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!