Why delay() doesn't work? [duplicate]
In this example:
$('#click').click(function() {
$('#delay').delay(2000).css('backg开发者_运维百科round-color', '#c30000');
});
Why does the delay()
call not delay the css()
call?
Check out http://api.jquery.com/delay/ and http://api.jquery.com/queue/
$(document).ready(function() {
$('#click').click(function() {
$('#delay').delay(2000).queue(function () {
$(this).css('background-color', '#c30000');
});
});
});
Use javascript's setTimeout():
setTimeout(function() {
$('#delay').css('background-color', '#c30000');
}, 2000);
From the documentation:
The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.
So, basically, in your scenario a timeout is a better approach than a delay as you're not between effects.
delay()
is for jQuery effects only.
Use a basic setTimeout
call instead.
精彩评论