Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and how should the promise() method be used?

Consider the code snippet below. What will be the difference between the start and end times displayed? Why is the .promise().done() not responding?

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>
like image 865
M0ns1f Avatar asked Nov 16 '25 06:11

M0ns1f


1 Answers

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

The time difference will be the length it takes for all the queued animations on the div elements to complete

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

It is. You just don't see the result in your example because the p tags are all hidden when the fadeOut() finishes, hence you cannot see the 'End Time` being output. If you use a different element to display that time it works fine:

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>
like image 123
Rory McCrossan Avatar answered Nov 18 '25 21:11

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!