Search code examples
jqueryvariablescountdown

jquery countdown


I am new to programming jquery php. I want to countdown a php time variable in jquery. For example time= 31233. How could i count down this like mm:ss?

Please help thanks


Solution

  • Try this:

    $(function() {
        var defaultTimer = 400, // Default amount of seconds if url variable is not found
            callback = function() {
                // Will be executed when the timer finishes
                alert("Time is up!");   
            };
    
        var counter = 1, timer, 
            match = document.location.href.match(/[\?|&]timer=(\d+)/i),
            totalTime = match ? match[1] : defaultTimer;
    
        timer = setInterval(function() {
            if (totalTime != -1 && !isNaN(totalTime)) {
                val = 'Time left: ' + (function() {
                    var m = Math.floor(totalTime / 60);
                    if (m < 10) {
                        return '0'.concat(m);
                    } else {
                        return m;
                    }
                })() + ':' + (function() {
                    var s = totalTime % 60;
                    if (s < 10) {
                        return '0'.concat(s);
                    } else {
                        return s;
                    }
                })();
    
                $('#counter').html(val);
                totalTime--;
            } else {
                window.clearInterval(timer);
                timer = null;
                callback();
            }
        }, 1000);
    });
    

    You can find an example here: http://jsfiddle.net/hHD4w/