jQuery .delay does not delay

余生长醉 提交于 2019-12-20 06:07:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!