This question already has answers here:
How to use setInterval and clearInterval?
                                
                                    (5个答案)
                                
                        
                7个月前关闭。
            
        

我有这个简单的页面:

    <!DOCTYPE html>
    <html>
    <body>

    <p>Click the second button to skip the timeout!</p>


    <button onclick="myStopFunction()">Stop the alert</button>

<script>
var myVar;

spamHi();

function spamHi() {
 console.log("Hi!");
 setTimeout(spamHi,3000);
}

function myStopFunction() {
  clearTimeout(spamHi);
}
</script>

</body>
</html>


spamHi()函数显示“ Hi!”。每3秒在控制台中输入一次。
myStopFunction()函数应该做的是
清除延迟以使控制台能够打印“ Hi!”立即无需等待3秒。

我怎样才能解决这个问题?

最佳答案

您需要获取setTimeout调用的返回值,然后将其传递给clearTimeout函数:

var timeout = setTimeout(spamHi, 3000);

clearTimeout(timeout);

10-07 19:56
查看更多