<script>
// 防抖函数
function debounce(fun, time) {
let timeout = null
let context = this
return function() {
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(() => {
fun.apply(context)
}, 300)
}
}
function handle() {
console.log(Math.random() * 10);
}
window.addEventListener('scroll', debounce(handle, 500))
// 节流函数
function throttle(fun) {
let context = this
let flog = true
console.log(11);
return function() {
if (!flog) return
flog = false
setTimeout(() => {
fun.apply(this)
flog = true
}, 500)
}
}
function sayHi() {
console.log(window.innerWidth);
}
window.addEventListener("resize", throttle(sayHi))
</script>
防抖与节流
最新推荐文章于 2023-03-27 14:48:08 发布