1.防抖函数
// 不再输入后1秒触发函数
function debounce(delay,callback){
let timer
return function (value) {
clearTimeout(timer)
timer = setTimeout(function () {
callback(value)
}, delay);
}
}
function fn(value){
console.log(value) // 回调函数
}
var debounceFunc = debounce(1000,fn)
input.addEventListener('keyup',function(e){
debounceFunc(e.targer.value)
})
2.节流函数
// 方法一
var btn = document.getElementById('input')
btn.addEventListener('click', throttle(submit, 2000), false)
function submit() {
console.log(e, this)
}
function throttle(fn, delay) {
var begin = 0
return function () {
var cur = new Date().getTime()
if (cur - begin > delay) {
fn.apply(this,arguments)
begin = cur
}
}
}
// 方法二
function throttle(func,delay) {
let timerOut
return function () {
if (!timerOut) {
timerOut = setTimeout(function() {
func()
timerOut = null
}, delay);
}
}
}
function handle() {
console.log(Math.random())
}
document.getElementById('button').onclick = throttle(handle,2000)