【发布时间】:2022-12-10 00:16:57
【问题描述】:
大家好,我是 JavaScript 的新手,正在观看一些关于 javascript 秒表的教程,我设法理解了大部分代码,但仍然有一些问题。想知道有人可以帮助解释间隔为 null 的目的是什么吗?这段代码是如何工作的?当我多次点击时,它是如何阻止函数再次运行的?
function start () {
if (interval) {
return
}
interval = setInterval(timer, 1000);
}
我粘贴了整个 JS 代码以提供更好的上下文
// Global variables
const time_el = document.querySelector('.watch .time');
const start_btn = document.getElementById('start');
const stop_btn = document.getElementById("stop");
const reset_btn = document.getElementById("reset");
let seconds = 0;
let interval = null;
// Event listeners
start_btn.addEventListener('click', start);
stop_btn.addEventListener("click", stop);
reset_btn.addEventListener("click", reset);
// Update the timer
function timer () {
seconds++;
// Format our time
let hrs = Math.floor(seconds / 3600);
let mins = Math.floor((seconds - (hrs * 3600)) / 60);
let secs = seconds % 60;
if (secs < 10) secs = '0' + secs;
if (mins < 10) mins = "0" + mins;
if (hrs < 10) hrs = "0" + hrs;
time_el.innerText = `${hrs}:${mins}:${secs}`;
}
function start () {
if (interval) {
return
}
interval = setInterval(timer, 1000);
}
function stop () {
clearInterval(interval);
interval = null;
}
function reset () {
stop();
seconds = 0;
time_el.innerText = '00:00:00';
}
【问题讨论】:
-
在 JS 中
null(以及其他一些值)是falsey。查看if函数内的start()条件。