Arul
Arul

Reputation: 491

Javascript countdown Issue. Want to clearInterval every click on button

Fiddle : http://jsfiddle.net/gLLvux07/

I am creating a countdown using javascript. its working fine when i click the button.

The issue is, if I click the button when countdown running, it will not start from 0.

I am trying to clear interval in the beginning of function, but not working.

HTML :

<style>
.container {
    width:50px;
    height:25px;
    overflow:hidden;
    margin-top:100px;
    margin-left:100px;
    border:2px solid #ddd;
}

.count {
    -webkit-transition: all 1;
    -moz-transition: all 1;
    transition: all 1;
}
</style>

<div class="container">
    <div class="count">
        <div>0</div>
    </div>  
</div>

<div style="text-align:center">
    <input type="button" onclick="countdown();" value="Click Me" />
</div>

Javascript Code :

function countdown() {
    clearInterval();
    $(".container .count").html("<div>0</div>")

    for(i=1;i<25;i++){
        $(".container .count").append("<div>"+i+"</div>");
    }

    var count1 = 0;
    var topmove = -10; 

    counting = setInterval(function(){                              
        $(".container .count").css({'-webkit-transform': 'translateY('+topmove+'px)'});
            count1 = count1+1;
            topmove = topmove-10;

            if(count1>40) {
                 clearInterval(counting);
            }  
    },100); 
 }

Upvotes: 0

Views: 139

Answers (2)

SeinopSys
SeinopSys

Reputation: 8937

clearInterval requires a parameter telling the script which countdown to stop. Try something like this:

var counting;
function countdown() {
    if (typeof counting === 'number') clearInterval(counting);
    $(".container .count").html("<div>0</div>")
    for(i=1;i<25;i++)
        $(".container .count").append("<div>"+i+"</div>");  
    var count1 = 0,
        topmove = -10;
    counting = setInterval(function(){
        $(".container .count").css({
            '-webkit-transform': 'translateY('+topmove+'px)'
        });

        count1 = count1+1;
        topmove = topmove-10;
        if (count1>40){
            clearInterval(counting);
        }
    },100);
}

Upvotes: 2

Mritunjay
Mritunjay

Reputation: 25882

Just define counting in global scope & do clearInterval(counting); in starting of function itself. You are not passing parameters to clearInterval.

DEMO

Upvotes: 4

Related Questions