1、防抖函数
防抖用于减少函数请求次数,对于频繁的请求,只执行这些请求的最后一次。
/**
* @param {function} func - 执行函数
* @param {number} wait - 等待时间
* @return {function}
*/
function debounce(func, wait = 300){
let timer = null;
return function(){
if(timer !== null){
clearTimeout(timer);
}
timer = setTimeout(func.bind(this),wait);
}
}
应用示例
let scrollHandler = debounce(function(e){
console.log('scroll')
}, 500)
window.onscroll = scrollHandler
2、节流函数
节流用于减少函数请求次数,与防抖不同,节流是在一段时间执行一次。
/**
* @param {function} func - 执行函数
* @param {number} delay - 延迟时间
* @return {function}
*/
function throttle(func, delay){
let timer = null
return function(...arg){
if(!timer){
timer = setTimeout(()=>{
func.apply(this, arg)
timer = null
}, delay)
}
}
}
使用示例
let scrollHandler = throttle(function(e){
console.log(e)
}, 500)
window.onscroll = scrollHandler
Vue与lodash
安装
npm i --save lodash
使用方法
// 写法一:
methods: {
// 注意function 不能省略
debounceSubmit: debounce(function() {
this.submit();
}, 500)
},
// 写法二:
created(){
this.debounceSubmit = debounce(this.submit, 500);
}
使用示例
1、对用户输入进行防抖处理
function handleInput(e) {
console.log(this);
console.log('input:', e.target.value);
}
function debounce(func, wait) {
let timer = null;
return function (...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(func.bind(this, ...args), wait)
}
}
let keyword = document.getElementById('keyword')
keyword.addEventListener('input', debounce(handleInput, 500))
在线demo: https://mouday.github.io/front-end-demo/debounce-demo.html
2、对浏览器滚动事件进行节流处理
#container {
height: 200vh;
}
function handleScroll() {
console.log('scrollTop:', document.body.scrollTop);
}
function throttle(func, wait) {
let timer = null;
return function (...args) {
if (timer) {
return;
}
timer = setTimeout(() => {
func.call(this, ...args);
timer = null;
}, wait)
}
}
document.addEventListener('scroll', throttle(handleScroll, 500))
在线demo:https://mouday.github.io/front-end-demo/throttle-demo.html
参考 10个非常实用的JS工具函数 vue , debounce 使用 前端性能优化 - 每一个前端开发者需要知道的防抖与节流知识