下面是我在面试中被问到的代码。
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/