Search code examples
javascriptjquerypromisedelayfadeout

jQuery fadeout time confusing with different results


Below is the code i was asked in interview.

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

I found running it here takes 12 seconds, while in this link it takes 8 Seconds..!

And above all the confusion is, in each loop the console prints the fadeout animation time increasing by 2 seconds, though it completes in total 2 seconds for each div.

Can anyone explain in details what's happening here exactly?

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">


Solution

  • in a fiddle here, you get two bonus div's for the "console" output (one inside the other ... so that explains the 2 x 2 second extra time

    in each loop the console prints the fadeout animation time increasing by 2 seconds, though it completes in total 2 seconds for each div.

    No, first div takes 0 seconds to fade
    Second div takes 2 seconds to fade completely
    Third div takes 4 seconds to fade completely
    Fourth div takes 6 seconds to fade completely
    Fifth div takes 8 seconds to fade completely

    Look closely and you'll see that they all start fading concurrently, at different rates