JS之函数节流

基本思想是:某些代码不可以在没有间断的情况连续重复执行。

第一次调用函数,创建一个定时器,在指定的时间间隔之后运行代码。当第二次调用该函数时,它会清除前一次的定时器并设置另一个。目的是确保只有在执行函数的请求停止了一段时间之后执行。

我今天使用的思想是:一个函数执行后,空格一定时间,再执行其他函数。

该模式的基本形式:

 

var processor = {
    timeoutId: null,
    //实际进行处理的方法
    performProcessor: function() {
        //....
    },
    process: function() {            //初始处理调用的方法
        clearTimeout(this.timeoutId);
        
        var that = this;
        this.timeoutId = setTimeout(function(){        //创建定时器
            that.performProcessor();
        }, 100);
    }
};

//------------------- test ---
processor.process();        //尝试开始执行

  用一个函数进行简化,这个函数可以自动进行定时器的设置和清除

 

function throttle(method, context) {
    clearTimeout(method.tId);
    //创建定时器
    method.tId = setTimeout(function() {
        //call()确保method()函数能在指定的context环境中执行
        //如果没有给出第二个参数,那么就在全局作用域内执行该方法
        method.call(context);
    }, 100);
}

我的代码:

 

var timeOut=null;
$('.xz_tips .bta,.xz_tips .bta2').mouseover(function (){
	timeOut&&clearTimeout(timeOut)												  
	$(this).parent().find('.xz_tips_info').show();
}).mouseout(function(){
	var _self='.xz_tips';
	timeOut=setTimeout(function(){$(_self).find('.xz_tips_info').hide()},100);	
})

$('.xz_tips').find('.xz_tips_info').hover(function(){
	timeOut&&clearTimeout(timeOut);				  
},function(){
	$(this).hide();	
})	

 

  

 

  

 

posted @ 2013-09-10 15:56  想望  阅读(216)  评论(0)    收藏  举报