javascript 函数节流
2017/06/05 标签:
javascript节流函数
转载:http://www.cnblogs.com/dolphinX/p/3403821.html
<script type="text/javascript">
n=0;
function resizehandler(){
console.log(new Date().getTime());
console.log(++n);
}
function throttle(method,delay){
var timer=null;
return function(){
var context=this, args=arguments;
clearTimeout(timer);
timer=setTimeout(function(){
method.apply(context,args);
},delay);
}
}
window.onresize=throttle(resizehandler,500);//因为返回函数句柄,不用包装函数了
</script>节流函数终极版:
function throttle(method,delay,duration){
var timer=null, begin=new Date();
return function(){
var context=this, args=arguments, current=new Date();;
clearTimeout(timer);
if(current-begin>=duration){
method.apply(context,args);
begin=current;
}else{
timer=setTimeout(function(){
method.apply(context,args);
},delay);
}
}
}节流函数变种
throttle: function(method,delay,duration){
//延迟delay秒执行,如果数据在delay秒内且duration秒内触发,则重新延迟delay秒执行(duration应小于delay),最快delay秒执行 最多延迟 (delay+duration)秒左右
var timmer=null, begin = new Date();
return function(){
var context=this, args=arguments, current=new Date();
if(!timmer){
begin = new Date();
timmer = setTimeout(function(){
method.apply(context,args);
timmer = null;
},delay);
}else{
if(current - begin <= duration){
clearTimeout(timmer);
timmer = setTimeout(function(){
method.apply(context,args);
timmer = null;
},delay)
}
}
}
}节流函数变种2
//持续执行事件中,maxdelay秒内没有触发过,则第一次触发立即执行,delay秒内如果再次触发,则延迟执行,最多延迟maxdelay秒或者满足条件秒
function throttle(method, delay, maxdelay, conditionFun) {
var timmer = null, begin = new Date();
return function () {
var context = this, args = arguments, current = new Date();
if (current - begin > maxdelay) {
begin = new Date();
console.log('a');
method.apply(context, args);
} else {
if (typeof (conditionFun) !== 'undefined' && conditionFun()) {
//如果满足条件执行,开始时间重新计算
begin = new Date();
clearTimeout(timmer);
timmer = null;
console.log('b')
method.apply(context, args);
} else {
clearTimeout(timmer);
timmer = setTimeout(function () {
console.log('c');
method.apply(context, args);
}, delay);
}
}
}
}
var count = 0;
window.onresize = throttle(function () { console.log(2) }, 3000, 5000, function () { count++; if (count > 10) { count = 0; return true; } else { return false } })
下一篇:
dom选择器
静水缘首页
文章分类
最新文章
- nodejs私钥加密公钥解密的一个例子
- uniapp和微信小程序判断程序运行在开发或者测试或者线上版本的方法分别是什么
- electron使用electron-builder打包后模块包含exe文件执行失败
- Compile is disallowed on the main thread, if the buffer size is larger than 4KB
- better-sqlite3简介及常用操作
- nodejs 操作数据库的库
- nodejs使用http-proxy库实现多个域名代理和同时代理websocket的例子,代理包含https和http两种协议
- iis配置反向代理
- javascript伪多线程代码
- ip所在地址段判断