Created
March 13, 2017 12:55
-
-
Save hereisfun/140a529af581ef68f696df327ea7bff3 to your computer and use it in GitHub Desktop.
节流函数,保证某一操作的最小时间间隔
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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