为什么debounce 是返回一个 函数? 因为,这样可以解决闭包问题!!!!!
function debounce(fn, delay, leading) {
let timer = null
leading = leading || false
return handle = function () {
clearTimeout(timer);
let _this = this
let _arguments = arguments
if (leading) {
let isCall
if (!timer) {
fn.apply(_this, _arguments)
isCall = true;
}
if (isCall) {
timer = setTimeout(() => {
isCall = false
fn.apply(this, arguments)
}, delay)
}
}
else {
timer = setTimeout(() => {
fn.apply(this, arguments)
}, delay)
}
}
}
// 二个参数 防抖函数
function debounce2(fn, delay) {
let timer = null
return function () {
clearTimeout(timer)
timer = setTimeout(() => { fn.apply(this, arguments) }, delay)
}
}
// 节流函数 定时器版
function throttle(fn,time){
let canUse = true ; // 设置一个开关
return function(){
if(!canUse ){ return false } // 如果开关已经关掉了就不用往下了
// if(canUse) fn.apply(this,arguments)//fn放这里是立即执行
canUse = false // 利用闭包刚进来的时候关闭开关
setTimeout( ( ) => {
fn.apply(this,arguments)//fn放这里是非立即执行,定时器结束才执行
canUse = true // 执行完才打开开关
},time)
}
// 节流函数 时间戳版
function throttle(fn, delay) {
let lastTime = 0
return function () {
let nowTime = new Date().getTime()
if (nowTime - lastTime > delay) {
fn.apply(this, arguments)
lastTime = nowTime
}
}
}
let aaa = function () {
console.log(this)
}
var search = document.querySelector(".search");
var _searchChange = jieliu(aaa, 1000);
search.oninput = _searchChange;