zoukankan      html  css  js  c++  java
  • 关于启动定时器和取消定时器的问题

    在js机制中,我们都知道,一般代码写在某个事件中的话,只有当触发事件,才会执行代码,比如

    $(selector).click(function(){alert('你好')});

    如上代码,只有在触发点击事件的时候,才会弹出 “你好” 的问候语;

    但是,在使用定时器的时候,不管是事件中,还是事件外,都会在加载的时候被执行,比如

    var timer = setInterval(play,speed);
    $('selector').hover(function(){
       clearInterval(timer); 
    },function(){
       timer = setInterval(play,speed); 
    })
    

    以上代码,我是在事件外开启了一个定时器,当鼠标经过selector的时候,关闭定时器,鼠标离开selector的时候,又会开启定时器。

    可是,上面的代码会开启两个定时器,而不是我们想要的只是开启一个,那么,如果下改造后

    var timer = setInterval(play,speed);
    $('selector').hover(function(){
       clearInterval(timer); 
    },function(){
       clearInterval(timer); 
       timer = setInterval(play,speed); 
    })
    

    记住,写在事件中的定时器,也会被加载的时候所开启,所以,务必在执行定时器的前面加上清除定时器。

  • 相关阅读:
    redis集群redis-cloud搭建
    Linux下搭建redis服务器
    mybatis主键返回
    分布式文件系统FastDFS
    mapper映射文件不发布
    dubbo发布和引用服务
    PageHelper分页插件
    F. Cards and Joy
    E. Paint the Tree 树形dp
    D. Sequence Sorting dp
  • 原文地址:https://www.cnblogs.com/yesw/p/4607751.html
Copyright © 2011-2022 走看看