Search code examples
javascripttimercountdown

stop javascript countdown timer with onclick event


i need help, i make a javascript function for countdown timer with progress bar, here is code

function progress(timeleft, timetotal, $element) {
    var progressBarWidth = timeleft * $element.width() / timetotal;
    $element.find('div').animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, 'linear').html('');
        $('#time_wrap').html('<span id="timer">'+timeleft+'</span>');
    if(timeleft > 0) {
        setTimeout(function() {
            progress(timeleft - 1, timetotal, $element);
        }, 1000);
    }else{
            setTimeout(function() {
            submitdata();
        }, 1000);
        }
    };

i need to stop timer with onclick event, ex: <input type="button" onclick="stoptimer();">

how to stop the timer with function stoptimer() ?


Solution

  • What you are looking for is clearTimeout.

    You can modify your code to be like:

    var timer = null;
    
    function progress(timeleft, timetotal, $element) {
        var progressBarWidth = timeleft * $element.width() / timetotal;
        $element.find('div').animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, 'linear').html('');
            $('#time_wrap').html('<span id="timer">'+timeleft+'</span>');
        if(timeleft > 0) {
            timer = setTimeout(function() {
                progress(timeleft - 1, timetotal, $element);
            }, 1000);
        } else{
            timer = setTimeout(function() {
                submitdata();
            }, 1000);
        }
    
        // You can use this to bind event only after the timer is set.
        // $('#stop-btn').on('click', function() { 
        //    clearTimeout(timer);
        // });
    };
    
    function stoptimer() {
        clearTimeout(timer);
    }