js 中函数的防抖和节流
//模拟用户输入时请求函数
function ajax(content) {
console.log('ajax request ' + content)
}
// 函数的防抖,类似于法师技能读条,每点击一次技能,技能都会重新引导,使用场景如搜索时用户输入信息
function debounce(func, delay) {
return function (argus) {
let that = this;
let _args = argus;
clearInterval(func.id);
func.id = setTimeout(function () {
func.call(that, _args); // call方法第一个参数确定新的this指向,后面可以有多个参数是一串参数列表
}, delay)
}
}
// 函数的节流,类似于fps游戏枪械的射击频率,即使一直按着左键,但是每秒射出的子弹是一定的,监听用户滑到底部加载更多
function throttle(fun, delay) {
let last,deferTimer
return function (argus) { //利用闭包的原理保存了last等变量
let now = +new Date(); // 当前时间转化为时间戳
let _args = arguments;
let that = this;
if (last && last < now + delay) {
clearInterval(deferTimer)
deferTimer = setTimeout(function () {
last = now;
fun.apply(that, _args); // apply最多接受两个对象,新的this指向,和argusArray参数数组(必须是array或者arguments对象)
}, delay)
} else {
last = now;
fun.apply(that, _args)
}
}
}
let throttleAjax = throttle(ajax, 5000);
let debouncejax = debounce(ajax, 1000);
let inputc = document.getElementById('test') //html中写一个id为test的input
inputc.addEventListener('keyup', function (e) {
// input 节流
// throttleAjax(e.target.value);
// input 防抖
debouncejax(e.target.value);
})