定时器时间清零!!

我想在屏幕滚动的时候把_time设为零,就是立马让divhide(),而不是关闭定时器
这样能做吗?

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title></title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
      <input type="button" value="点击" class="show"/>  
    <div class="dis">hello</div>  
    <script>  
     $(function(){
           var _time = 3000;
              $('.show').click(function(){
                  timer3 = setTimeout(function(){
                            $(".dis").hide();                    
                    },_time);    
              })
              
              window.scroll(function(){
                                          
              })
     })
            
    </script>  
</body>
</html>
阅读 6.4k
5 个回答

直接在屏幕滚动的时候,将div hide()不就行了吗,一定要用定时器兜个圈子吗?

哪位给编辑过了

$(function() {
    var _time = 3000;
    $('.show').click(function() {
        timer3 = setTimeout(hide, _time);
    })
    window.onscroll = hide;

    function hide() {
        $(".dis").hide();
    }
})

如果你的timer3已经在执行了,你在设置_time为0,应该是不行的。
为什么不直接在滚动时直接设置$(".dis").hide();了?

clear掉定时器就行了,然后$(".dis").hide();

$(function(){
   var _time = 3000;
    var timer3 = null;
      $('.show').click(function(){
          timer3 = setTimeout(function(){
                    $(".dis").hide();                    
            },_time);    
      })
      
      window.scroll(function(){
            clearTimeout(timer3);  
            $(".dis").hide();                  
      })
 })

不行,你调用一次的setTimeout函数就是往JS的定时器执行队列中注册了一个定时器,除非调用clearTimeout函数,否则你是清除不掉定时器的~~

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题