开发者

How to delay a call to a function

开发者 https://www.devze.com 2023-02-21 05:54 出处:网络
I have the following code which calls another function, i.e.: $(\'input[name=\'f01\']:checked\').each(function() {

I have the following code which calls another function, i.e.:

$('input[name='f01']:checked').each(function() {
 开发者_Go百科                                 setCBCollection(this);
});

How can I put a delay of say 2 seconds on each call to setCBCollection(this)?


Using setTimeout:

$('input[name="f01"]:checked').each(function() {
    var element = this;
    setTimeout(function() {
        setCBCollection(element);
    }, 2000);
});

setTimeout schedules a function to be called N milliseconds later (roughly, these things are not precise).

Note that we grab this to a variable local to the event handler function, and then the function we pass into setTimeout is a closure over that variable (because otherwise, the meaning of this will get lost). More details:

  • Closures are not complicated
  • You must remember this

Off-topic: There's a syntax error in your original, you're using ' within a '-quoted string without escaping it. I changed it to " in my code above.

0

精彩评论

暂无评论...
验证码 换一张
取 消