节流和防抖函数


/**
 * 节流函数
 * @param {Funtion} method 回调函数
 * @param {Object} context 上下文地址
 * @param {number} delay 延迟时间ms
 */
function throttle(method, context, delay) {
    delay = delay || 500;
    var currentDate = new Date();
    method.startTime = method.startTime || 0;
    if (currentDate - method.startTime > delay) {
        method.call(context);
        method.startTime = new Date();
    }
    else {
        clearTimeout(method.timer);
        method.timer = setTimeout(function () {
            throttle(method, context, delay);
        }, 50);
    }
}


/**
 * 防抖函数
 * @param {Funtion} method 回调函数
 * @param {Object} context 上下文地址
 * @param {number} delay 延迟时间ms
 */
function debound(method, context, delay) {
    delay = delay || 200;
    clearTimeout(context.deboundId);
    context.deboundId = setTimeout(function () {
        method.call(context);
    }, delay);
}

posted @ 2018-12-27 21:06  大西瓜的一片净土  阅读(159)  评论(0编辑  收藏  举报