简体   繁体   中英

Jquery / JavaScript Countdown Timer From Passed Hour, Minutes and Seconds Variables

Ok so i found this code at This Post and im looking to add hour along with minutes and seconds. Can someone please help with this - Im not very good with jquery:(

Here is the code:

<div id=timer></div>
<script type="text/javascript">
    var timeoutHandle;
    function countdown(minutes, seconds) {
        function tick() {
            var counter = document.getElementById("timer");
            counter.innerHTML =
                minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
            seconds--;
            if (seconds >= 0) {
                timeoutHandle = setTimeout(tick, 1000);
            } else {
                if (minutes >= 1) {
                    // countdown(mins-1);   never reach “00″ issue solved:Contributed by Victor Streithorst
                    setTimeout(function () {
                        countdown(minutes - 1, 59);
                    }, 1000);
                }
            }
        }
        tick();
    }

    countdown(1, 30);
</script>

So, to be clear, I need to pass 3 variables: countdown(hour, mins, secs); - Many thanks!

So after some time playing around with this code I think I have figured it out. Im not sure if its the best way of doing it but from my testing it appears to work up to 24 hours.

Here is the code; if you can add to it or improve it please do as im not very good with java script:(

<div id=timer></div>
<script type="text/javascript">
var timeoutHandle;
function countdown(hours, minutes, seconds) {
function tick() {
var counter = document.getElementById("timer");
counter.innerHTML = hours.toString() + ":" + (minutes < 10 ? "0" : "") + String(minutes) + ":" + (seconds < 10 ? "0" : "") + String(seconds);
seconds--;
if (seconds >= 0) {
timeoutHandle = setTimeout(tick, 1000);
} else {
if (minutes >= 1) {
setTimeout(function () { countdown(hours, minutes - 1, 59); }, 1000);
}
else if (hours >= 1) {
setTimeout(function () { countdown(hours - 1, 59, 59); }, 1000);
}

}
}
tick();
}

countdown(2,30,10);
</script>

I hope someone finds this useful and helpful:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM