javascript 未捕获ReferenceError,它说startTimer未定义,即使它已定义

bxjv4tth  于 2023-03-16  发布在  Java
关注(0)|答案(2)|浏览(468)
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>

基本上,当调用pauseWatch函数时,我希望它清除startTimer间隔,但它说它没有定义,即使它不确定它是否与变量范围有关,但即使它是,我也不知道如何修复它
我尝试重新安排一些代码,但似乎没有任何帮助

chy5wohz

chy5wohz1#

你需要在全局作用域中定义startTimer变量(在函数之外),这样就可以在startWatch()函数之外使用它。

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() {

...
scyqe7ek

scyqe7ek2#

StartTimer位于函数内部,无法调用。我在代码开头添加了var startTimer;,并对函数startWatch()进行了一些编辑

var startTimer;

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

请访问https://replit.com/@JLRR222/problem#index.html

相关问题