javascript - 为什么以及如何使用 promise() 方法?

标签 javascript jquery

考虑下面的代码片段。显示的开始时间和结束时间有何不同?为什么 .promise().done() 没有响应?

function getMinsSecs() {
  var dt = new Date();
  return dt.getMinutes() + ":" + dt.getSeconds();
}

$("#start").on("click", function() {
  $("p").append("Start time: " + getMinsSecs() + "<br />");
  
  $("div").each(function(i) {
    $(this).fadeOut(1000 * (i * 2));
  });
  
  $("div").promise().done(function() {
    $("p").append("End time: " + getMinsSecs() + "<br />");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<button id="start">Start time</button>

最佳答案

what will be the difference between the start and end times displayed?

时间差将是 div 元素上所有排队动画完成所需的时间

why the .promise().done() isn't responding ?

是的。您只是在示例中看不到结果,因为 fadeOut() 完成时 p 标记全部隐藏,因此您看不到正在输出的“结束时间” .如果您使用不同的元素来显示该时间,它可以正常工作:

function getMinsSecs() {
  var dt = new Date();
  return dt.getMinutes() + ":" + dt.getSeconds();
}

$("#start").on("click", function() {
  $("p").append("Start time: " + getMinsSecs() + "<br />");
  $("div").each(function(i) {
    $(this).fadeOut(1000 * (i * 2));
  });
  $("div").promise().done(function() {
    $("span").append("End time: " + getMinsSecs() + "<br />");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<button id="start">Start time</button>

<span></span>

关于javascript - 为什么以及如何使用 promise() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46631550/

相关文章:

javascript - ASP.NET Partial Postback 表单值问题

javascript - 如何在用于在网页中播放 .swf 的 Flash 播放器中使用控件?

javascript - 错误 : Attempting to set key on an object that is immutable and has been frozen

jquery - 更改 li 内 span 内内容的 css

javascript - jquery getJson 的反缓存代码

javascript - 为什么js函数在另一个函数内部工作但不能单独工作

来自字符串的 Javascript 嵌套对象

jquery - 获取点击链接的ID

jquery - 为什么隐藏 "select"选项?

javascript - 使用 javascript 检查输入字段文本框中的多个单词