clearTimeout不起作用

使用定时器时,有两个按钮,一个是设置定时器,一个是清除定时器,但是clearTimeout并没有起作用,控制台上还是输出,请问是为什么,哪里出错了?

代码如下:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Document</title>

    <script>

       var settime=null;

        function insert(){

            settime=window.setTimeout(showalert,3000);

        }

        function showalert(){

            console.log("这是显示语句");

        }

        function clear(){

            window.clearTimeout(settime);

        }

    </script>

</head>

<body>

    <div id="a">

      <h3>setTimeout</h3>

      <button onclick="insert()">显示语句</button>

      <button onclick="clear()">取消显示</button>

    </div>

</body>

</html>


慕莱坞森
浏览 1225回答 3
3回答

繁花不似锦

啊啊,老兄,这种问题之前我也遇到过,很无措。原因: clear 是个关键字,你试试改个名字,比如 clear1 就行了。---补充抱歉,回答的不太正确。你可以这样试试(如下代码),它会打印出:ƒ clear() { [native code] }。说明在事件处理的内部的作用域中有一个 clear 方法,它排的比较靠前,表现的就像一直会覆盖你定义的 clear 方法。<button&nbsp;onclick="(function()&nbsp;{&nbsp;console.log(clear)&nbsp;})()">Click</button>

胡子哥哥

你的取消按钮不会执行的 函数名字是关键字

红糖糍粑

&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; 可以在启动定时器的时候先清理下已有的timeout&nbsp; &nbsp; ```&nbsp; &nbsp; function insert(){&nbsp; &nbsp; &nbsp; &nbsp; if(settime) window.clearTimeout(settime);&nbsp; &nbsp; &nbsp; &nbsp; settime=window.setTimeout(showalert,3000);&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; function clear(){&nbsp; &nbsp; &nbsp; &nbsp; if(settime) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.clearTimeout(settime);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; settime = null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; ```&nbsp; &nbsp; 另外,clear为关键字,属于document对象的api,可以尝试如下代码:&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; ```&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; document.clear = function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("clear是关键字");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script>&nbsp; &nbsp; <a href="#" onclick="clear()">click me</a>&nbsp; &nbsp; ```&nbsp; &nbsp; 所以,还需要修改清除定时器的函数名。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript