防抖
在n秒后執(zhí)行五慈,如果在n秒內(nèi)觸發(fā)纳寂,n就會(huì)重新計(jì)算,
/*
* fn [function] 需要防抖的函數(shù)
* wait [number] 毫秒泻拦,防抖期限值
*/
function debounce(fn, wait) {
var timeout = null;
return function (e) {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this, arguments);
}, wait);
};
}
在React項(xiàng)目中使用:
src/@utils/debounce.js
/*
* fn [function] 需要防抖的函數(shù)
* wait [number] 毫秒毙芜,防抖期限值
*/
export const debounce = (fn, wait) => {
var timeout = null;
return function (e) {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this, arguments);
}, wait);
};
}
在需要使用防抖的組件類
import {debounce} from "../../@utils/debounce"
scroll = debounce((e) => {
//...
}, 500)
<div onScroll={(e) => { this.scroll(e) }}>
節(jié)流
在n秒內(nèi)只執(zhí)行一次,
/*
* fn [function] 需要防抖的函數(shù)
* wait [number] 毫秒争拐,防抖期限值
*/
function throttle(fn, wait) {
let canRun = true;
return function () {
if (!canRun) return;
canRun = false;
setTimeout(() => {
fn.apply(this, arguments);
canRun = true;
}, wait);
};
}
在React項(xiàng)目中使用:
src /@utils/throttle.js
/*
* fn [function] 需要防抖的函數(shù)
* wait [number] 毫秒腋粥,防抖期限值
*/
export const throttle = (fn, wait) => {
let canRun = true;
return function () {
if (!canRun) return;
canRun = false;
setTimeout(() => {
fn.apply(this, arguments);
canRun = true;
}, wait);
};
}
在需要使用防抖的組件類
import { throttle } from "../../@utils/throttle"
scroll = throttle((e) => {
//...
}, 500)
< div onScroll = {(e) => { this.scroll(e) }}>