Javascript Countdown not working

I have this javascript code

 function updateClock() {
        time = time + 1;
       var  mins = 1;
       var secs = 50
       var mins = parseInt(mins/ 60);
       var secs = time - mins * 60;

        mins = mins.toString();
        secs = secs.toString();

        if (mins.length < 2)
            mins = "0" + mins;
        if (secs.length < 2)
            secs = "0" + secs;


        var timeDisp = document.getElementById("timerDisp");
        timeDisp.innerText = mins + ":" + secs;
    }

It is counting how much time has passed, but what if I want to do a countdown? (or do the reverse) instead of keeping track of the time, I want to give if a definite time then as time goes by the time decreases, let's say 1 minute and 15 seconds, how would I execute that on the given code?

Answers:

Answer

You can execute your updateClock() every 1 second with setTimeout() to create a countdown.

var time;
function UpdateClock() {
    time = time - 1;

    if (time > 0) {
        setTimeout(UpdateClock, 1000); // 1000 miliseconds
    }

    var mins = parseInt(time / 60, 10);
    var secs = time - mins * 60;

    mins = mins.toString();
    secs = secs.toString();

    if (mins.length < 2)
        mins = "0" + mins;
    if (secs.length < 2)
        secs = "0" + secs;

    timeDisp.innerText = mins + ":" + secs + " left";
}

function StartCountdown(countdowntime) {
    time = countdowntime;
    updateClock();
}
Answer

You could use setInterval() for your countdown. See http://www.w3schools.com/jsref/met_win_setinterval.asp.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.