在变量中使用clearInterval

时间:2018-06-01 00:07:17

标签: javascript

我正在创建一个简单的JavaScript Timer。首先,这是我与之合作的代码:

//Variables used for the timer
var timer = "waiting",
    seconds = 0,
    minutes = 0,
    extraFill1 = "",
    extraFill2 = "";

//Check whether to start or stop the timer
function toggleClock() {
    if (timer === "waiting") {
        setInterval(start, 1000);
        timer = "executing";
        document.getElementById("btn").innerText = "Stop";
    }
    else {
        clearInterval(start);
        timer = "waiting";
        document.getElementById("btn").innerText = "Start";
    }   
}

//Increment seconds and display correctly
function start() {
    seconds++;

    //Add a leading zero for 1 digit numbers (seconds)
    if (seconds < 10 || seconds === 60) {
        extraFill1 = "0";
    }
    else {
        extraFill1 = "";
    }

    //Increment minute when seconds reaches 60
    if (seconds === 60) {
        minutes += 1;
        seconds = 0;
    }

    //Add a leading zero for 1 digit numbers (minutes)
    if (minutes < 10) {
        extraFill2 = "0";
    }
    else {
        extraFill2 = "";
    }

    //display results
    document.getElementById("result").innerHTML = extraFill2 + minutes + ":" + extraFill1 + seconds;
}

在我的第一个函数toggleClock()中,我已声明如果timer !== waiting,则我们执行clearInterval(start)。如果clearInterval(start),我想timer === "executing。这不起作用(我认为是因为它有本地范围?)。为了解决这个问题,我尝试写作:

var myTimer = setInterval(start, 1000);

当我想启动计时器时,我打算调用myTimer。相反,一旦页面加载(并声明变量),间隔就会启动。

我如何设置一个功能的间隔(按钮点击),能够在以后停止/清除间隔(通过按相同的按钮)?

1 个答案:

答案 0 :(得分:1)

您之前需要将clearInterval结果传递给setInterval;如果您没有将功能传递给clearInterval,则会将其传递给intervalID。例如:

let clockInterval;
function toggleClock() {
  if (timer === "waiting") {
    clockInterval = setInterval(start, 1000);
    timer = "executing";
    document.getElementById("btn").innerText = "Stop";
  }
  else {
    clearInterval(clockInterval);
    timer = "waiting";
    document.getElementById("btn").innerText = "Start";
  }   
}