logicb0mb
logicb0mb

Reputation: 121

How do I access a local variable in JavaScript, specifically for the setInterval() and clearInterval() methods?

I am making a Pomodoro Timer in JS.

I am using a 'Start' and a 'Stop' button for it. When the Start button is clicked, the timer starts off at 25:00 min and goes down to 00:00 min.

I have done this with the Date() object and the setInterval() method. What I want is for the user to have a 'Stop' button if they wanna stop the timer before 25 minutes are done.

To do this, I will need to access the variable x in which the state of setInterval() is stored. This x needs to be passed to clearInterval(x). This is how I stop the timer.

Now, I have 2 separate startTimer() and stopTimer() functions for the separate buttons[onclick]. The state of setInterval i.e. variable x is in the startTimer() function whereas to stop the timer I need to access this local variable inside another function stopTimer()

How do I access this local variable?

Here is the relevant code:

function startTimer() {

    var toDateTime = new Date().getTime() + 1500000; //adding 25 mins to current time
    console.log("startFunction is on with endDate: " + toDateTime);

    //use setInterval to update every second
    var x = setInterval(function() {
        timerFunc(toDateTime)
    }, 1000); //need to access this var x in stopTimer
} //end startTimer function


function stopTimer() {
    clearInterval(x); //can't access 'x' here, workaround this.
}

Upvotes: 0

Views: 108

Answers (1)

Lemayzeur
Lemayzeur

Reputation: 8525

assign x without var or declare outside function to make scope available to stopTimer function

var x;
function startTimer(){

    var toDateTime = new Date().getTime() + 1500000;       //adding 25 mins to current time
    console.log("startFunction is on with endDate: "+toDateTime);
    //use setInterval to update every second
    clearInterval(x); //Clear interval before setInterval to prevent creation of multiple interval 
    x = setInterval(function(){timerFunc(toDateTime)}, 1000); //need to access this var x in stopTimer
}//end startTimer function


function stopTimer(){
    clearInterval(x);    //can't access 'x' here, workaround this.
}

Upvotes: 1

Related Questions