以下是我在采访中被问到的代码。
Start&的区别是什么?在这种情况下结束时间?
我发现在这里运行它需要 12秒 ,而在this link需要 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 />");
});
});
&#13;
<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">
&#13;
答案 0 :(得分:2)
我会尝试在您的代码中解释它:
// 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(8) )秒。
我希望它有所帮助!
答案 1 :(得分:1)
8是正确的答案。承诺将在8s后完成,因为最后一个div的最长衰落持续时间是4 * 2(s)。 在此网站上运行的代码段有一个错误。它还包括2个不属于您的代码的div。尝试替换
console.log(1000 * (i * 2));
到这个
console.log($(this));
你将能够知道出了什么问题
答案 2 :(得分:1)
在这里,你可以获得两个额外的奖励,用于&#34;控制台&#34;输出(一个在另一个内...所以这解释了2 x 2秒的额外时间
在每个循环中,控制台打印淡出动画时间增加2秒,但每个div总共完成2秒。
不,第一个div需要0秒才能淡出 第二个div需要2秒才能完全淡出 第三个div需要4秒才能完全淡出 第四个div需要6秒才能完全消失 第五个div需要8秒才能完全消失
仔细观察,你会发现它们都以不同的速度同时开始消退