/** * generate a throttling function * * @param {Function}fn The callback of event * @param {Number}interval time interval */ functionthrottle(fn, interval) { var last = 0
returnfunction() {
var context = this
var args = arguments
var now = +newDate()
if (now - last >= interval) { last = now fn.apply(context, args) } } } var betterScroll = throttle(function() { console.log('滚动事件触发') }, 1000)
/** * generate a debounce function * * @param {Function}fn The callback of event * @param {Number}delay time interval */ functiondebounce(fn, delay) { var timer = null returnfunction () {
/** * generate a throttle function * * @param {Function}fn The callback of event * @param {Number}delay time interval */ functionthrottle(fn, delay) { var last = 0, timer = null
returnfunction () {
var context = this
var args = arguments
var now = +newDate()
if (now - last < delay) { clearTimeout(timer)
timer = setTimeout(function() { last = now }, delay) } else { last = now