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); 
    })
    

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

  • 相关阅读:
    lintcode-60-搜索插入位置
    lintcode-57-三数之和
    lintcode-55-比较字符串
    lintcode-52-下一个排列
    lintcode-51-上一个排列
    lintcode-49-字符大小写排序
    lintcode-47-主元素 II
    lintcode-45-最大子数组差
    lintcode-44-最小子数组
    Charles抓包
  • 原文地址:https://www.cnblogs.com/yesw/p/4607751.html
Copyright © 2011-2022 走看看