Search code examples
javascriptmomentjscountdown

Moment.js countdown not decrementing more than a second


I'm using moment.js to create a three minute countdown. However, every time the page loads, the timer decrements by one second and stops at 2:59. Printing out variables such as future and difference seems to yield normal results, however, so I believe that my error lies in the countdown. What is wrong with my countdown?

Here's my code:

    <script type="text/javascript">
        $(document).ready(function(){
            var now = moment();
            var future = moment(now).add(3, 'm');
            var difference = future - now;
            var duration = moment.duration(difference, 's');
            var interval = 1000;

            setInterval(function() {
                if(duration.asSeconds() <= 0) {
                    clearInterval(intervalId);
                    document.getElementById("clock").innerHTML = moment(duration.asSeconds()).format("m:s");
                }

                duration = moment.duration(duration.asSeconds() - 1, 's');
                document.getElementById("clock").innerHTML = moment(duration.asSeconds()).format("m:s");
            }, interval);
        });
    </script>

Solution

  • you can change that to be something like this:

    if (moment.duration(future - moment()).asSeconds() <= 0) {

    and change

    duration = moment.duration(duration.asSeconds() - 1, 's');

    to be

    duration = moment.duration(moment.duration(future - moment()).asSeconds(), 's');

    because you're closure is capturing the value of duration above but never really updating it.