search

Home  >  Q&A  >  body text

javascript - 滚动条滚动停止怎么控制运行中的定时器

这里的功能是点击按钮,过三秒弹出随机的数据
假如现在三秒还没有过,而我滚动了滚动条,我希望滚动了滚动条就立马结束掉定时器
也就是说让他立马显示数据,要怎么实现????

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        html,body{margin:0;padding:0;height:3000px;overflow-y:scroll;border:1px solid red}
        .aaa{width:100px;height:100px;text-align:center;line-height:100px;border:1px solid red}
    </style>
</head>
<body>
    <input type="button" value="click" id="btnclick" />
    <p class="aaa"></p>
    <script src="http://cdn.bootcss.com/jquery/2.2.1/jquery.js"></script>
    <script>
        $(function(){
            
            var arr=['你好','hello','beybey'];
            var timer = null;
            var flag = false;
            var timeout = 3000;
            
            $("#btnclick").click(function(){
                
                flag = true;
                clearTimeout(timer);
                
                timer = setTimeout(function(){
                    $(".aaa").html(''+arr[Math.floor(Math.random()*arr.length)]+'');                    
                },timeout)
            })
            
            $(window).scroll(function(){
                if(flag){
                    //这里怎么处理???
                }
            })
        })
    </script>
      
</body>
</html>
阿神阿神2896 days ago353

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-10 17:33:37

    <script>
        $(function(){
            
            var arr=['你好','hello','beybey'];
            var timer = null;
            var flag = false;
            var timeout = 3000;
    
            $("#btnclick").click(function(){
                flag = true;
                clearTimeout(timer);
                
                timer = setTimeout(function(){
                    $(".aaa").html(''+arr[Math.floor(Math.random()*arr.length)]+'');   
                    flag = false;                 
                },timeout)
            })
            
            $(window).scroll(function(){
                if(flag){
                    clearTimeout(timer);
                    $(".aaa").html(''+arr[Math.floor(Math.random()*arr.length)]+''); 
                    flag = false; 
                }
            });
    
        })
    </script>
    
    我理解的楼主的意思是:点击后三秒之内滚动,则立即改变;三秒过后则滚动无效;是这样吗?

    reply
    0
  • Cancelreply