javascript - jQuery 淡出时间与不同结果混淆

标签 javascript jquery promise delay fadeout

下面是我在面试中被问到的代码。

What would be the difference between Start & End time in this case?

我发现在这里运行它需要12秒,而在 this link 中运行它需要12秒需要8秒..!

最令人困惑的是,在每个循环中,控制台打印的淡出动画时间增加了 2 秒,尽管每个 div 总共完成了 2 秒。

谁能详细解释一下这里到底发生了什么?

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

$("input").on("click", function() {

  $("p").append("Start time: " + getMinsSecs() + "<br />");

  $("div").each(function(i) {
    console.log(1000 * (i * 2));
    $(this).fadeOut(1000 * (i * 2));
  });

  $("div").promise().done(function() {
    $("p").append("End time: " + getMinsSecs() + "<br />");
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>

<input type="text" id="inp">

最佳答案

我会尝试在您的代码中解释它:

// if there are 5 <div> elements on the page, what will be the difference between the start and end times displayed?

/**
 * This function gets the current date and prints 
 * the minutes and seconds in the following format
 * mm:ss
 */
function getMinsSecs() {
  var dt = new Date();
  return dt.getMinutes() + ":" + dt.getSeconds();
}

/**
 * Here we are adding a click event listener to the
 * input present in the HTML.
 */
$("input").on("click", function() {

  // This line appends to the p present in the HTML
  // the text with the current minutes and seconds (start time)
  // and the a break line.
  $("p").append("Start time: " + getMinsSecs() + "<br />");

  // This line goes through each div present in the HTML fading out each div multiplying it by the i (index).
  $("div").each(function(i) {
      console.log(i);
    console.log(1000 * (i * 2));
    //The fadeout function lasts the amount of milliseconds passed as an argument
    $(this).fadeOut(1000 * (i * 2));
  });

  // This line waits til every function called over
  // the divs end (this is what the promise function does).
  $("div").promise().done(function() {

    // This function is called after all the
    // fadeout calls got executed and prints again
    // the minutes and seconds appending the current minutes
    // and seconds (end time)
    $("p").append("End time: " + getMinsSecs() + "<br />");
  });

});

根据评论,第一个项目会立即淡出,因为 i = 0,那么您还剩下四 (4) 个 div,4 * 2 = 8 所以开始时间和结束时间之间的差异将为八 (8) 秒。

希望对您有帮助!

关于javascript - jQuery 淡出时间与不同结果混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540571/

相关文章:

javascript - 404 未找到静态文件 React JS | NGINX

javascript - coffeescript 中的 AMD 模块没有缩进整个文件?

javascript - POST 请求 : return status reports

javascript - Angular 中的 promise 工厂

node.js - 链接 promise 更新 Mongoose 中的引用文档

javascript - 如何在 javascript 中将名为 active 的类更改为链接的 active 属性

javascript - 如何在不使用 eval() 的情况下将数组的内容用作变量?

javascript - 在 javascript 中使用 'continue' 标志?

javascript - 递归地将嵌套的xml转换为嵌套的html

javascript - 如何在 Node.js 中为 Promise 运行 for 循环