Andreea Tirgovatu
Andreea Tirgovatu

Reputation: 111

setInterval reset at click

I have this code:

 $(document).ready(function(){
        var count = 0;
        var clicks= 0;
        $(".press").click(function() {
            count++;
            clicks++;
            console.log(count);
            $('#animation2').html("My current count is: "+clicks);
            if(count==1){
                count=0;
                if($('.animation img').css('left') == '100px'){
                    $('.congrats').css('display','block');
                    $("#startClock").css('display','block');
                    $(".press").css('display','none');
                    $('.animation img').css('left','0');
                    var counter=0;
                    span.innerHTML = counter;
                }else{
                    $('.animation img').animate({ "left": "+=10px" }, 1 );
                }
            }
        });  
    span = document.getElementById("count");
        $("#startClock").click(function() {
            clicks=0;
            $("#animation2").css('display','block');
            $('#animation2').html("My current count is: "+clicks);
            var counter =30;
            $('.congrats').css('display','none');
            $('.press').css('display','block');
            $(this).css('display','none');
           setInterval(function() {
             counter--;
              if (counter >= 0) {
                 span.innerHTML = counter;
              }
              if (counter === 0) {
                 $("#startClock").css('display','block');
                 $('.press').css('display','none');
                 clearInterval(counter);
               }
             }, 1000);
        });
    });

This code have a counterdown whitch must be reset when I click button with id=startClock the second time. If I click twice setInterval decrease 2 second suddenly.

Upvotes: 0

Views: 84

Answers (1)

G Roy
G Roy

Reputation: 166

You are not using setInterval and clearInterval correctly. When you call setInterval, it returns an ID that you can use later with clearInterval. Here is an example :

var counter = 30;
var my_interval = setInterval(function(){
   counter--;
   if(counter <= 0) {
        clearInterval(my_interval);
   }
}, 1000);

This would countdown from 30 every second until counter reaches 0, then it would stop.

I suggest you go read about timeouts and intervals here

Upvotes: 1

Related Questions