Jasmine Lognnes Jasmine Lognnes - 19 days ago 6
Javascript Question

How to get function to return only when done?

In this http://jsfiddle.net/kuox9ax2/ have I a timer that counts down.


  • When it reaches zero it starts over. It shouldn't do that.

  • As JS is asynchronous I can't figure out how to get it to call a function only when it have reached zero.



I have tried to as
return true
in
startTimer()
, but then I run into that JS is asynchronous, so it returns true right away.

Can someone show how to solve these two issues?



function startTimer(duration, display) {
var timer = duration, minutes, seconds;

setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);

minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;

display.textContent = minutes + ":" + seconds;

if (--timer < 0) {
timer = duration;
}
}, 1000);
}

window.onload = function() {
var time = 5, display = document.querySelector('#time');
var isDone = startTimer(time, display);

if (isDone) {
alert("a");
}
};

<div>Timeout in <span id="time">00:00</span> minutes</div>




Answer

Store your interval in a variable and call clearInterval when reaching 0. Javascript functions can be passed as parameters, typically named callbacks. Simply pass a function as a parameter and call it when needed.

function startTimer(duration, display, callback) {
  var timer = duration,
    minutes, seconds;

  var myInterval = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      timer = duration;
      
      // clear the interal
      clearInterval(myInterval);

      // use the callback
      if(callback) {
          callback();
      }
    }
  }, 1000);
}

window.onload = function() {
  var time = 5,
    display = document.querySelector('#time');
  var isDone = startTimer(time, display, function() { alert('done'); });

  if (isDone) {
    alert("a");
  }
};
<div>Timeout in <span id="time">00:00</span> minutes</div>

Comments