How to delay a call to a 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.
精彩评论