问题
How can I set the html of an element, wait 2 seconds, then set the html to something else?
Example: $("div").html("clicked").delay(2000).html("2 seconds have passed");
What happens: the div gets "2 seconds have passed" off the bat, instead of saying "clicked" for 2 seconds, then displaying "2 seconds have passed".
Do I need to do something like, .delay(2000, function() { $("div").html("2 seconds have passed"); })
?
Live example here: http://jsbin.com/UfaYusU/1/edit
Thanks!
回答1:
$.delay is used to delay animations in a queue, not halt execution.
Try this:
setTimeout(function() {
// Do something after 2 seconds
}, 2000);
回答2:
.delay()
by default only works with animating functions, you can use .promise()
method:
$("div").html("clicked").delay(2000).promise().done(function() {
$(this).html("2 seconds have passed");
});
回答3:
Use setTimeout()
if you want to run some code after a delay...
$("button").click(function(e) {
$("div").html("clicked");
setTimeout(function() {
$("div").html("2 seconds have passed");
}, 2000);
});
Here's an updated version of your jsbin...
来源:https://stackoverflow.com/questions/18984979/jquery-delay-does-not-delay