Search code examples
javascripthtmlsetinterval

Uncaught ReferenceError, it says startTimer is not defined even though it is


const startBtn = document.querySelector('.startBtn');
const pauseBtn = document.querySelector('.pauseBtn');
const ResetBtn = document.querySelector('.resetBtn');
const time = document.querySelector('.time');

let seconds = 0;
let secondsStr = '00';
let minutes = 0;
let minutesStr = '00';
let hours = 0;
let hoursStr = '00';
let timeText = `${hoursStr}:${minutesStr}:${secondsStr}`;
time.textContent = timeText;

function addSecond() {
    seconds++;
    secondsStr = seconds.toString();
    if (seconds < 10) {
        secondsStr = `0${secondsStr}`;
    }
    
    if(seconds >= 60) {
        seconds = 0;
        minutes++;
        minutesStr = minutes.toString();
        if (minutes < 10) {
            minutesStr = `0${minutesStr}`;
        }
        
        if(minutes >= 60) {
            minutes = 0;
            hours++;
            hoursStr = hours.toString();
            if (hours < 10) {
                hoursStr = `0${hoursStr}`;
            }
        }
    }
    timeText = `${hoursStr}:${minutesStr}:${secondsStr}`;
    time.textContent = timeText;
}

startBtn.addEventListener('click', startWatch);
pauseBtn.addEventListener('click', pauseWatch);

function startWatch() {
    const startTimer = setInterval(addSecond, 1000);
}

function pauseWatch() {
    clearInterval(startTimer);
}
<div class="stopwatch">
        <div class="time"></div>
        <div class="stopwatchBtns">
            <button class="startBtn stopwatchBtn">Start</button>
            <button class="pauseBtn stopwatchBtn">Pause</button>
            <button class="resetBtn stopwatchBtn">Reset</button>
        </div>
    </div>

basically when the pauseWatch function is called i want it to clear the startTimer interval but it says that it is not defined even though it is im not sure if its to do with the variable scope but even if it is i dont know how to fix it

i tried rearranging some code but nothing seem to help at all


Solution

  • You need to define the startTimer variable in the global scope (outside of the function). This will allow it to be used outside of your startWatch() function.

    const startBtn = document.querySelector('.startBtn');
    const pauseBtn = document.querySelector('.pauseBtn');
    const ResetBtn = document.querySelector('.resetBtn');
    const time = document.querySelector('.time');
    
    let seconds = 0;
    let secondsStr = '00';
    let minutes = 0;
    let minutesStr = '00';
    let hours = 0;
    let hoursStr = '00';
    let timeText = `${hoursStr}:${minutesStr}:${secondsStr}`;
    time.textContent = timeText;
    
    let startTimer; // define variable in global scope
    
    function addSecond() {
    
    ...