Skip to content

Instantly share code, notes, and snippets.

@hereisfun
Created March 13, 2017 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hereisfun/140a529af581ef68f696df327ea7bff3 to your computer and use it in GitHub Desktop.
Save hereisfun/140a529af581ef68f696df327ea7bff3 to your computer and use it in GitHub Desktop.
节流函数,保证某一操作的最小时间间隔
//fn为要节流的操作,interval为最小操作间隔
var throttle = function(fn, interval){
var timer,
_fn = fn;//保存要延时的函数的引用
return function(){
var that = this;
var arg = arguments;
//如果有未完成的计时器,则不进行操作
//即还没满足最小操作间隔
if(timer){
return;
}
_fn.apply(that, arg);
//每次执行完操作后放一个时长为interval的计时器
timer = setTimeout(function(){
clearTimeout(timer);
timer = null;
}, interval)
}
}
var btn = document.getElementById('btn');
btn.onclick = throttle(function(){
console.log('click!');
}, 2000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment