JS防抖节流

1,防抖:在事件被触发n秒之后执行,如果在此期间再次触发事件,则重新开始计时。

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

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

2,节流:如果持续触发一个事件,则在一定的时间内只执行一次事件

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版,2 表定时器版
 */
function throttle(func, wait ,type) {
    if(type===1){
        var previous = 0;
    }else if(type===2){
        var timeout;
    }
    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)
            }
        }
    }
}
// 调用,返回一个闭包函数
let getInputDebounce = debounce(ajaxFun,1000, true);
    console.log(getPhoneDebounce)
    Dom.addEventListener('keyup',(e)=>{
        console.log(e.target.value)
            getInputDebounce(e.target.value);
    })

function ajaxFun(inputValue){}

 3,横杠转驼峰法

var f = function(s){
    return s.replace(/-w/g,function(x){
      return x.slice(1).toUpperCase();
    })
}

参考:https://www.jianshu.com/p/c8b86b09daf0

本想把日子过成诗,时而简单,时而精致,不料日子却过成了一首歌,时而不靠谱,时而不着调
原文地址:https://www.cnblogs.com/chuanq/p/12162425.html