最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery .click() handler can't accept setTimeout() around the function - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a comment  | 

4 Answers 4

Reset to default 8

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.

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.

发布评论

评论列表(0)

  1. 暂无评论