学习:
function debounce(fn, time) {
var settime = null
return function() {
if(settime !== null){
clearTimeout(settime)
}
settime = setTimeout(fn, time)
}
}
function handle() {
console.log(Math.random())
}
window.addEventListener('scroll', debounce(handle, 1000))
以上是开源,滑动结束后一秒才会调用handle
function throttle(fn, time) {
var pre = Date.now()
return function() {
var context = this
var args = arguments
var now = Date.now()
if(now - pre >= time) {
func.apply(context, args)
pre = Date.now()
}
}
}
function handle() {
console.log(Math.random())
}
window.addEventListener('scroll', throttle(handle, 1000))
以上是节流,持续一秒以上调用时,handle函数一秒调用一次