背景:
今天在研究某个网站首页的公共文件JS时,发现了两个比较有意思的函数,分别是throttle和debounce,分别是函数节流和函数去抖。这两个函数目的相同,都是为了减少函数执行次数,优化页面。适用场景比较多,譬如页面在执行resize,scroll,mouseover这类函数时,可以防止其反复执行而消耗资源。
不同点:
1. throttle : 第一次请求便生成一个相关动作timer,后续如果仍有该操作,若该timer仍存在,则不继续生成,否则,再生成一个timer。
2. debounce : 大致功能类似于throttle,不同点在于新的请求过来之后,timer将会被重置,直到timer执行。
简单的自己实现了一下,大致写法如下:
var tool = {
event : {
// 函数节流
throttle : function(method, delay, context) {
var timer = null
context = context || this
return function() {
if (!timer) {
timer = setTimeout(function() {
timer = null
method.apply(context, arguments)
}, delay || 100)
}
}
},
// 函数去抖
debounce : function(method, delay, context) {
var timer = null,
start = new Date()
context = context || this
return function() {
var current = new Date()
clearTimeout(timer)
if (current - start >= delay) {
timer = setTimeout(function() {
method.apply(context, arguments)
}, delay || 100)
}
}
}
}
}
var outputFn = function() {
console.log(1)
}
// 函数去抖 —— 每次都刷新
$(window).resize(tool.event.debounce(outputFn, 1000))
// 函数节流 —— 固定频率不刷新
//$(window).resize(tool.event.throttle(outputFn, 1000))