JS 函数防抖 函数节流

平滑滚动到页面顶部

const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); } } // 事例 scrollToTop()

/**

函数防抖


* @param { function } func
* @param { number } wait 延迟执行毫秒数
* @param { boolean } immediate true 表立即执行,false 表非立即执行
*/
export function debounce(func,wait,immediate) {
let timeout;
return function () {
let context = this;
let args = arguments;

if (timeout) clearTimeout(timeout);
if (immediate) {
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait);
if (callNow) func.apply(context, args)
}
else {
timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
}

/**

函数节流

 


* @param { function } func 函数
* @param { number } wait 延迟执行毫秒数
* @param { number } type 1 表时间戳版,2 表定时器版
*/
export function throttle(func, wait ,type) {
let previous, timeout;
if(type===1){
previous = 0;
}else if(type===2){
timeout = null;
}
return function() {
let context = this;
let args = arguments;
if(type===1){
let now = Date.now();

if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}else if(type===2){
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}

}
}

猜你喜欢

转载自www.cnblogs.com/wkk2020/p/12515127.html