0

Here I use Codeigniter and MomentJS, How to run the 'alert()' function when 'contdown timer' has run out

in Main.JS

var timeEvent = <?=$timeEvent?>;
var timeNow = <?=now('America/Santiago')?>;
var diff = timeEvent - timeNow;
var duration = moment.duration(diff*1000, 'milliseconds');
var interval = 1000;

setInterval(function(){
  duration = moment.duration(duration - interval, 'milliseconds');
  $('#result').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds());
}, interval);
Firmansyah
  • 106
  • 12
  • 27
  • Look at this! http://stackoverflow.com/questions/16129157/countdown-timer-using-moment-js#answer-38022466 – Leo May 16 '17 at 02:53
  • put an if statement after the duration is set and check the value of duration, if it's <= 0 fire your alert. – Rick Calder May 16 '17 at 02:54
  • As an aside, note that `setInterval()` isn't guaranteed to run at exactly the specified interval, so if you're displaying a countdown it is normal practice to factor the current time into your calculation rather than just subtracting the same value every time. – nnnnnn May 16 '17 at 02:57

1 Answers1

1

Surely it's this simple no?

setInterval(function(){
  duration = moment.duration(duration - interval, 'milliseconds');
  if( duration <= 0 ) {
    alert("Done");
  }
  $('#result').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds());
}, interval);
Rick Calder
  • 18,310
  • 3
  • 24
  • 41