JavaScript秒表SetInterval忽略ClearInterval

时间:2018-11-25 14:03:34

标签: javascript

我正在进行秒表监视,在我告诉它停止或根本不停止之后,setInterval似乎正在自行重启。

我想要的是,当我按下Stop时,setInterval会停止循环,但会保持其编号,除非单击重置按钮。

const sw = {
    time: 0,
    reset: ()=>{
        clearInterval(sw.stopWatch)
        sw.time = 0
    },
    stop: ()=>{
        clearInterval(sw.stopWatch)
        console.log("stop")
    },
    stopWatch: ()=>{
        setInterval(function(){
            sw.time ++
            document.getElementById("time").innerHTML = sw.time
        }, 1000)
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="index.js"></script>
</head>
<body>
    <div id="time">0</div>
    <button onclick="sw.stopWatch()">Start</button>
    <button onclick="sw.stop()">Stop</button>
    <button onclick="sw.reset()">Reset</button>
    
</body>
</html>

2 个答案:

答案 0 :(得分:3)

clearInterval使用计时器ID,而不是函数。您正在尝试使用sw.stopWatch(它是一个函数)来调用它。

相反,您需要保存setInterval返回的ID,并将其传递给clearInterval

const sw = {
    time: 0,
    reset: ()=>{
        clearInterval(sw.timerId)
        sw.time = 0
    },
    stop: ()=>{
        clearInterval(sw.timerId)
        console.log("stop")
    },
    stopWatch: ()=>{
        sw.timerId = setInterval(function(){
            sw.time ++
            document.getElementById("time").innerHTML = sw.time
        }, 1000)
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="index.js"></script>
</head>
<body>
    <div id="time">0</div>
    <button onclick="sw.stopWatch()">Start</button>
    <button onclick="sw.stop()">Stop</button>
    <button onclick="sw.reset()">Reset</button>
    
</body>
</html>

答案 1 :(得分:0)

您应该保存间隔ID以便清除

const sw = {
    intervalId: 0,
    time: 0,
    reset: ()=>{
        clearInterval(sw.intervalId)
        sw.time = 0
        document.getElementById("time").innerHTML = 0
    },
    stop: ()=>{
        clearInterval(sw.intervalId)
        console.log("stop")
    },
    stopWatch: ()=>{
        sw.intervalId = setInterval(function(){
            sw.time ++
            document.getElementById("time").innerHTML = sw.time
        }, 1000)
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="index.js"></script>
</head>
<body>
    <div id="time">0</div>
    <button onclick="sw.stopWatch()">Start</button>
    <button onclick="sw.stop()">Stop</button>
    <button onclick="sw.reset()">Reset</button>
    
</body>
</html>