Search code examples
javascriptjquerytimercountdown

JavaScript Countdown Timer Code [JS]


I'm currently trying to get a countdown timer working but, I don't know JavaScript at all.

<script>
$(document).ready(function (e) {
    var $timer = $("#timer");

    function update() {
        var myTime = $timer.html();
        var ss = myTime.split(":");
        var dt = new Date();
        dt.setHours(0);
        dt.setMinutes(ss[0]);
        dt.setSeconds(ss[1]);

        var dt2 = new Date(dt.valueOf() - 1000);
        var temp = dt2.toTimeString().split(" ");
        var ts = temp[0].split(":");

        $timer.html(ts[1]+":"+ts[2]);
        setTimeout(update, 1000);
    }

    setTimeout(update, 1000);
});
</script>

But I've stumbled upon a problem. So I want it to stop on 00:00, but it continues going. Also at 2 minutes left and no time remaining I want it to execute some code.

At no time remaining (00:00) I want it to simply redirect to a page and at 2 minutes remaining I want it to run some custom code (Which I have).

But I have no idea on how to make it run at a time and make it stop at a time.

Can anyone help me with this?


Solution

  • Try

        $timer.html(ts[1]+":"+ts[2]);
    
             if((ts[1]==="02") &&(ts[2]==="00")){
                  //custom code at 02:00
               }
    
             if((ts[1]==="00") &&(ts[2]==="00")){
                  //Make the redirect
              }
             else{ 
                  setTimeout(update, 1000);
                 }
    

    DEMO