uview's throttling and anti-shake method js

uview source address

The throttling and anti-shake JS method I searched on the Internet before sometimes has inexplicable freezes in the small program. I feel that there is no problem in the experience of the uview framework I used recently. The source code is as follows

throttling

let timer; let
    flag
/**
 * 节流原理:在一定时间内,只能触发一次
 *
 * @param {
    
    Function} func 要执行的回调函数
 * @param {
    
    Number} wait 延时的时间
 * @param {
    
    Boolean} immediate 是否立即执行
 * @return null
 */
function throttle(func, wait = 500, immediate = true) {
    
    
    if (immediate) {
    
    
        if (!flag) {
    
    
            flag = true
            // 如果是立即执行,则在wait毫秒内开始时执行
            typeof func === 'function' && func()
            timer = setTimeout(() => {
    
    
                flag = false
            }, wait)
        }
    } else if (!flag) {
    
    
        flag = true
        // 如果是非立即执行,则在wait毫秒内的结束处执行
        timer = setTimeout(() => {
    
    
            flag = false
            typeof func === 'function' && func()
        }, wait)
    }
}
export default throttle

anti shake

let timeout = null

/**
 * 防抖原理:一定时间内,只有最后一次操作,再过wait毫秒后才执行函数
 *
 * @param {
    
    Function} func 要执行的回调函数
 * @param {
    
    Number} wait 延时的时间
 * @param {
    
    Boolean} immediate 是否立即执行
 * @return null
 */
function debounce(func, wait = 500, immediate = false) {
    
    
    // 清除定时器
    if (timeout !== null) clearTimeout(timeout)
    // 立即执行,此类情况一般用不到
    if (immediate) {
    
    
        const callNow = !timeout
        timeout = setTimeout(() => {
    
    
            timeout = null
        }, wait)
        if (callNow) typeof func === 'function' && func()
    } else {
    
    
        // 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法
        timeout = setTimeout(() => {
    
    
            typeof func === 'function' && func()
        }, wait)
    }
}

export default debounce

2023.6.30

Hidden danger! ! ! There are currently several throttling methods found on the Internet (PS: anti-shake not tested), once an error occurs inside the event that needs throttling, all methods that call throttling will not be executed (a similar page will appear that can be operated, throttling The event is not triggered after the button of the flow is clicked), it is suspected that the throttling method is stuck due to an error report, the solution is to throw an exception in the internal event package layer of the throttling try catch

Supongo que te gusta

Origin blog.csdn.net/weixin_38566069/article/details/130527508
Recomendado
Clasificación