"Start/Resume", "Stop/Reset" Buttons for Timer Not Working

Hi folks!

I’m having a little trouble getting some of the buttons of my timer app to work: I have a “Start” button with two functions (link here: https://jsfiddle.net/MenelikMakonnen/230xtgmb/)

  1. Start the timer (which works)
  2. Resume timer countdown if paused (haven’t coded out pause button yet)

See code here:

 $('.start-resume').click(function(){ 
	            $('#number').addClass("on"); 
              clearInterval(myVar);
     //if paused, then click to resume(make a state for if myVar == -1)
     
     if (myVar == -1){
      myVar = setInterval (function(){
      	seconds++;
        number.inerHTML = seconds;
        }, 1000);
        //else
        }else{
        clearInterval(myVar);
        myVar = -1
      }
     	}); 

When I click the start button while the timer is running, for some reason, it speeds up the timer

My other button, the “Stop/Reset” button, won’t stop the timer when clicked (see code here)

$('.stop-reset').click(function(){
     var myVar
       if (myVar == -1){
       clearInterval(myVar);
       startCountDown();
       }
     });

Thanks in advance for any help!

Hi @blitzkreig, first off nice design!

Double-check your start button JavaScript event handler:

const startCountDown = () => {
    var myvar = setInterval(() => secondsPassed(document.getElementById("number")), 1000);
}

$(".start-resume").click(function(){
    $('#number').addClass("on"); 
    startCountDown();
});

setInterval creates a “timer” every and it starts ticking away until you stop it.

startCountdown is creating a new timer every time you click btn.start-resume. That means if you click it 3x, it’s going to create 3 timers. Because of your secondsPassed function, that’s going to fire every second for every timer.

Therefore to address your problem, you probably want to prevent a user from starting another timer if there’s already one running.

Second note: I recommend improving your variable names. It goes a long way in understand complex logic, which you’re starting to encounter in your app.

@nicknish, thanks for the design compliment :grinning: . I see what you are saying about the Start button…now what about the “Stop/Reset” button?

Shouldn’t it clear the running interval per the clearInterval line in my code here:

$('.stop-reset').click(function(){
     var myVar
       if (myVar == -1){
       clearInterval(myVar);
       startCountDown();
       }
     });

???

1 Like

I think you’re on the right path, but because of the var myVar line, the variable is going to be undefined.

Instead, you need to move your variable outside of this click handler block. The variable should contain the timer id that is returned when you use setInterval. Here’s the concept, but you’ll need to put it altogether.

var timerId = setInterval( ... ); // returns some Number that represents the timer id
clearInterval(timerId); // stops the correct timer
1 Like

@nicknish, @JM-Mendez, I’m not getting this… where do I put this: var timerId = setInterval( ... ); // returns some Number that represents the timer id clearInterval(timerId); ???

This is my javascript code right now:

let seconds = 60; //(duration for timer to run)
var myTimer;

const secondsPassed = (e) => {
    console.log("yea mon time ah move yunno!")
    //inside this function, new variable called minutes
    let minutes = Math.round((seconds-30)/60);
    //now going to add another variable inside function for remaining seconds
    let remainingSeconds = seconds % 60;
    
    if (remainingSeconds < 10){
        remainingSeconds = "0" + remainingSeconds;
    }

    //Output the result in an element with id="number"
    e.innerHTML = minutes + ":" + remainingSeconds

    //once remaining seconds reach none, interval is over, so write some text
    if( seconds == 0){
        clearInterval("number"); //countdown ends and ceases numeric display
        e.innerHTML= 'Buzz!!'; //..and will display the alphabetic display, "Buzz!!"....temporary placeholder....will link to a buzz sound later
    }else{
        seconds--; //decrements as long as seconds do not equal zero
    }
}

const startCountDown = () => {
    var myTimer = setInterval(() => secondsPassed(document.getElementById("number")), 1000) //displays countdown per the number id from html sheet
}

 //on button
 $('.state-1').click(function(){
 	$('#number').addClass("on");
  $(".radar-background").show(); 
 });


 $(".start-resume").click(function(){ 
    startCountDown(); //calls startCountDown function from above: "startCountDown = () => {}"
     //if paused, then click to resume(make a state for if myVar == -1)
     
/* this code didn't work
     if (myTimer == -1){
      myVar = setInterval (function(){
      	seconds++;
        number.inerHTML = seconds;
        }, 1000);
        //else
        }else{
        clearInterval(myTimer);
        myTimer = -1
      }
    });
    */
     }); 
      //pause button
      $('#pause').on('click', function() {
      clearInterval("number")
      });
      
      //off button
      
      $('.state-2').click(function(){
 	clearInterval();
 	$('#number').removeClass("on"); 
  
 }); 
      
     //stop/reset button
     
     $('.stop-reset').click(function(){
       clearInterval(myTimer);
     });
     
        


	$(".state-2").click(function(){ 
	    $(".radar-background").hide(); 
	});

Hi @blitzkreig. There’s a few problems here. When you have a variable in an outer scope, and you redeclare the variable in an inner scope using the var keyword, then the variable in the outer scope won’t be modified.

var myTimer = "outside value";

const startCountDown = () => {
  // by using the "var" keyword,
  // you're declaring a new variable for this
  // function.
  var myTimer = "inside value";
}

startCountDown();
console.log(myTimer); // "outside value"

If you want to change the myTimer variable somewhere else, you can’t redeclare the variable:

var myTimer;

const startCountDown = () => {
  // don't use var here
  myTimer = setInterval(() => secondsPassed(document.getElementById("number")), 1000) //displays countdown per the number id from html sheet
}

You are also using clearInterval incorrectly.

When you assign a variable to setInterval, it will return the timerID. Therefore you must use the same variable if you wish to clear. So…

// not this
clearInterval("number")

// but this
const number = setInterval(/*...*/)
clearInterval(number)

Here’s a nice article explaining it further

http://vaidehijoshi.github.io/blog/2015/01/06/the-final-countdown-using-javascripts-setinterval-plus-clearinterval-methods/

vscode’s intellisense would have pointed out this error, and eslint would have pointed out the variable reassignment error.

Let the tools help you.

@JM-Mendez, I think I tried that before too, to no effect. But I will read that link that you posted and try it again. Swear…I have no patience for javascript sometimes lol!

Javascript is a mess. That’s why tools were created to help iron out alot of this.

Intellisense, eslint, etc. Use the tools and let them help you. Otherwise you’re just shooting in the dark. I won’t even troubleshoot your code without copying it to my editor. I wouldn’t even know where to start.

@JM-Mendez it is a mess lol!:tired_face:

@blitzkreig not with the right tools! :wink: