码迷,mamicode.com
首页 > Web开发 > 详细

js 节流函数 throttle

时间:2016-03-23 06:23:36      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

/*
* 频率控制 返回函数连续调用时,fn 执行频率限定为每多少时间执行一次
* @param fn {function}  需要调用的函数
* @param delay  {number}    延迟时间,单位毫秒
* @param immediate  {bool} 给 immediate参数传递false 绑定的函数先执行,而不是delay后后执行。
* @param debounce  {bool} 给 immediate参数传递false 绑定的函数先执行,而不是delay后后执行。debounce
* @return {function}实际调用函数
*/

 var throttle = function(fn, delay, immediate, debounce) {
    var curr = +new Date(),//当前事件
        last_call = 0,
        last_exec = 0,
        timer = null,
        diff, //时间差
        context,//上下文
        args,
        exec = function () {
            last_exec = curr;
            fn.apply(context, args);
        };
    return function () {
        curr = +new Date();
        context = this,
        args = arguments,
        diff = curr - (debounce ? last_call : last_exec) - delay;
        clearTimeout(timer);
        if (debounce) {
            if (immediate) {
                timer = setTimeout(exec, delay);
            } else if (diff >= 0) {
                exec();
            }
        } else {
            if (diff >= 0) {
                exec();
            } else if (immediate) {
                timer = setTimeout(exec, -diff);
            }
        }
        last_call = curr;
    }
};

 

 

var setval =  function(){
    var mydate = new Date();
    var s = mydate.getSeconds();
    var ms = mydate.getMilliseconds();
    document.getElementById("ipt").value=s+":"+ms;

}

//以下两种绑定方法都可以,特别是jquery绑定时.注意 $("#btn")[0]
//document.getElementById("btn").onclick = throttle(function(){ setval(); },1000,true,false); 
$("#btn")[0].onclick = throttle(function(){ setval(); },1000,true,false);

 

js 节流函数 throttle

标签:

原文地址:http://www.cnblogs.com/BinBinGo/p/5309504.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!