您现在的位置:首页 >> 前端 >> 内容

前端节流功能实现教程

时间:2018/2/21 10:41:11 点击:

  核心提示:p点击事件执行后需要冷却1秒后再次点击才有效p id=p0/pfunction throttle(handler, wait) {var lastTime = 0,nowTime;return fun...

p点击事件执行后需要冷却1秒后再次点击才有效

<p id="p">0</p>

function throttle(handler, wait) {
    var lastTime = 0,
        nowTime;
    return function (e) {
        nowTime = new Date().getTime();
        if(nowTime - lastTime > wait) {
            handler.apply(this, arguments);
            lastTime = nowTime;
        }
    }
}

var p = document.getElementById('p');

function pClick() {
    this.innerHTML = parseInt(this.innerHTML) + 1;
}
p.onclick = throttle(pClick, 1000);

作者:网络 来源:ppSilence的