1. 程式人生 > 其它 >【轉發】vueSSR剖析

【轉發】vueSSR剖析

//=>防抖:每隔wait時間只可以執行一次
function debounce(func, wait, immediate) {
let result = null,
timeout = null;

        return function(...args) {
            let context = this,
                // 如果immediate為true  並且沒有其他定時器存在,now為true,會立即執行
                now = immediate && !timeout;
            //=>只要觸發這個函式,先清除一遍定時器,確保每次只有一個定時器在等待
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                timeout = null;
                if (!immediate) result = func.call(context, ...args);
            }, wait);
            //=>如果now為true,則立即執行函式,由於有定時器的存在,所以下次觸發的時候,timeout有值,now的值為false
            if (now) result = func.call(context, ...args);

            return result;
        }
    };



    //=>節流:假設wait為100,事件觸發了2000,那麼在這2000時間中,事件會觸發20次
    function throttle(func, wait) {
        let timeout = null,
            result = null,
            previous = 0; //=>上次執行時間點

        return function(...args) {
            let now = new Date, //=>獲取本地時間
                context = this;
            //=>remaining小於等於0,表示上次執行至此所間隔時間已經超過一個時間間隔wait
            let remaining = wait - (now - previous);
            if (remaining <= 0) {
                clearTimeout(timeout);
                previous = now;
                timeout = null;
                result = func.apply(context, args);
            } else if (!timeout) {
                timeout = setTimeout(() => {
                    previous = new Date;
                    timeout = null;
                    result = func.apply(context, args);
                }, remaining);
            }
            return result;
        }
    }