Search code examples
javascripthtmlbuttoncountdown

How to fix time skipping every click button to countdown? (Or reset countdown every click)


My countdown run normally if i click it once. But if i click it for several times, it skipping time. Here's my codes:

<input type="submit" value="Countdown" id="countdown" onclick="countdown_init()" />
<div id="countdown_text"></div>

<script type="application/javascript">
    var countdown;
    var countdown_number;
    var number = document.getElementById('countdown_text');
    function countdown_init() {
        countdown_number = 6;
        countdown_trigger();
    }

    function countdown_trigger() {
        if(countdown_number > 0) {
            countdown_number--;
            number.innerHTML = countdown_number;
            if(countdown_number > 0 ) {
                countdown = setTimeout('countdown_trigger()', 1000);
            }
        }
        if(number.innerHTML == "0"){
            document.getElementById('countdown_text').innerHTML = "";
        }
    } 
</script>

How to make countdown timer reset every i clicked the countdown button again and again?


Solution

  • just clear it in your init function:

    function countdown_init() {
        clearTimeout(countdown);
        countdown_number = 6;
        countdown_trigger();
    }