[笔记]关于JavaScript定时器如何清除和重启

定时器的清除和重启方法:

//
var t=setInterval(fun1,500) //fun1是你的函数
var fun1=function(){
    //写入你的函数;
}
clearInterval(t)//清除定时器
t=setInterval(fun1,500)//重新开始定时器

提示:要先清除,后设置,否则定时器永远清除不了。

例子:

一个可复用的延时显隐下拉菜单的js(抓元素和show();hide();等方法基于jQuery)

//顶部导航下拉列表
    function showhide(objMouseenter,objshow){
        var timer = null;
        //移入显示
        $(objshow).mouseenter(function(){
            clearTimeout(timer);
        });
        $(objMouseenter).mouseenter(function(){
            clearTimeout(timer);
            $(objshow).show();
        });        
        //移出设置定时器隐藏
        $(objMouseenter).mouseleave(function(){            
            timer = setTimeout(function() {
                $(objshow).hide();
            }, 500);
        }); 
        $(objshow).mouseleave(function(){
            timer = setTimeout(function() {
                $(objshow).hide();
            }, 500);
        });
    }
    showhide('#navFollow','#qrCode');

 

posted @ 2018-02-03 17:15  我的五年  阅读(27)  评论(0)    收藏  举报  来源