多次使用setInterval方法导致clearInterval不能成功关闭

发布于 2021-05-19 06:59:34

在多次点击显示系统时间按钮的情况下,再点击停止显示系统时间,这时发现无法停止。

原因

1、多次点击显示系统时间按钮的话,会导致setInterval的ID值不断变化,每点一次ID值加1。
2、这样clearInterval获取到的ID值就只是当前的ID值。
3、之前的对应ID值发生的事件就无法停止。多次点击没有把之前的任务覆盖,而是增加了。

解决办法

加一个flag标记,使得setInterval只能执行一次,并且必须在clearInterval执行后才能执行第二次。形成相互约束。

可参看知识点:https://www.itwenda.com/course/js/js-ji-shi-qi.html#a3

<html>
    <head>
        <title>幸运好抽奖-小游戏</title>
        <style>
            .con{width:300px;margin:0 auto;}
            .show{width:100%;text-align:center;}
            .title{
                color:#40AA53;
                font-size:30px;
                font-weight:bold;
            }
            .shownum{
                border:2px solid #40AA53;
                height:50px;
                line-height:50px;
                color:#40AA53;
                font-weight:bold;
            }
            .btn{
                background:#40AA53;
                color:#ffffff;
                border-radius: 16px;
                margin:10px auto;
                height:30px;
                line-height:30px;
                
            }
        </style>
        
     
    </head>
    <body>
        <div class="con">
            <div class="show title">抽奖结果</div>
            <div class="show shownum" id="shownum">即将开始</div>
            <div class="show btn" onclick="kaishi();">开始</div>
            <div class="show btn" onclick="zanting();">暂停</div>
            
        </div>
           <script>
           //flag标记
            var flag = true;
            // 创建4位随机数
            function creatnum(){
               return Math.floor(Math.random()*(9999-1000))+1000;
            }
            
            //
            function kaishisuiji(){
                document.getElementById("shownum").innerHTML=creatnum();
            }
            
            function kaishi(){
               //设置权限flag,使start、stop都只能执行一次
                if(flag){
                    bz=setInterval(kaishisuiji,5);
                    flag = false;
               }
                
            }
            
            function zanting(){
                if(!flag){
                    clearInterval(bz);
                    flag =true;
                }
                
            }
            
        </script>
    </body>
</html>



关注公众号,了解更多it技术(it问答网

0 条评论

发布
问题