0

Hey I'm currently practicing jquery by building a time countdown which you can click to pause or resume. But the clearInterval() is not working. Everytime I click the circle it just creat a new countdown.I don't know why.

var status="pause";
var timeleft=1500;

$("#circle").click(function(){
    var timer;
    if(status==="pause"){
        status="start";
        alert(status);
         timer=setInterval(function(){
            $("#timer").text(Math.floor(timeleft/60)+":"+timeleft%60);      
            timeleft--;
        },1000);
    }
    else if(status==="start"){
        status="pause";
        alert(status);
        clearInterval(timer);
    }

});
Adjit
  • 10,134
  • 12
  • 53
  • 98
Kyle Yeh
  • 5
  • 4
  • Note that you don't really need the `status` variable. The `timer` variable can store this information. If it's `null`, the timer isn't running, otherwise it's the ID of a running timer (non-zero, which is `true` inside an if). You just need to put `timer = null` after the `clearInterval`. – klenium May 26 '17 at 15:23
  • @klenium The `status` variable is for checkings of other onclick functions of my pomodoro clock.But thanks for that tip anyway. – Kyle Yeh May 26 '17 at 16:40
  • Yes, I knew that. – klenium May 27 '17 at 10:08

2 Answers2

5

Your 'timer' variable is scoped inside the click handler. This means a new one will be created every time. To keep only a single one it should be scoped outside that handler.

Taplar
  • 24,788
  • 4
  • 22
  • 35
0

the timer variable needs to be in a parent scope so it retains its value through multiple clicks. What is the scope of variables in JavaScript?

var status="pause";
var timeleft=1500;
var timer;  //<----changed scope

$("#circle").click(function(){
    if(status==="pause"){
        status="start";
        alert(status);
         timer=setInterval(function(){
            $("#timer").text(Math.floor(timeleft/60)+":"+timeleft%60);      
            timeleft--;
        },1000);
    }
    else if(status==="start"){
        status="pause";
        alert(status);
        clearInterval(timer);
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="circle">start</button>
<div id="timer"><div>
smurtagh
  • 1,187
  • 9
  • 17