什么是防抖&节流?如何在react项目中使用防抖节流?

防抖

在n秒后执行,如果在n秒内触发,n就会重新计算,

/*
* fn [function] 需要防抖的函数
* wait [number] 毫秒,防抖期限值
*/
function debounce(fn, wait) {
    var timeout = null;
    return function (e) {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            fn.apply(this, arguments);
        }, wait);
    };
}

在React项目中使用:

src/@utils/debounce.js

/*
* fn [function] 需要防抖的函数
* 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) }}>

节流

在n秒内只执行一次,

/*
* fn [function] 需要防抖的函数
* 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项目中使用:

src /@utils/throttle.js

/*
* fn [function] 需要防抖的函数
* 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) }}>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。