1. 函数防抖
/**
* 函数防抖
* @param {function} func 一段时间后,要调用的函数
* @param {number} wait 等待的时间,单位毫秒
*/
function debounce(func, wait) {
// 设置变量,记录 setTimeout 得到的 id
var timerId = null;
return function (...args) {
if (timerId) {
// 如果有值,说明目前正在等待中,清除它
clearTimeout(timerId);
}
// 重新开始计时
timerId = setTimeout(() => {
func(...args);
}, wait);
}
}
<input type="text" id="txt">
<script>
var txt = document.getElementById("txt");
// 调用 debounce 函数来将事件处理函数变为一个防抖函数
var debounceHandle = debounce(function(event){
console.log(event.target.value);
}, 500)
txt.onkeyup = (event) => {
debounceHandle(event);
}
</script>
2. 函数节流
/**
* 方案一:使用时间戳
* @param {要进行节流的函数} func
* @param {间隔时间} wait
* @returns
*/
function throttle(func, wait) {
var args; // 存储函数参数
var previous = 0; // 一开始的默认时间
return function () {
var now = new Date(); // 获取最新的时间戳
args = arguments; // 获取参数
// 进行时间戳的判断,如果超出规定时间,则执行
if (now - previous > wait) {
func.apply(null, args);
previous = now;
}
}
}
/**
* 方案二:使用定时器
* @param {要节流执行的函数} func
* @param {节流的时间间隔} wait
* @returns
*/
function throttle(func, wait) {
// timeout 存储计时器返回值
// args 存储参数
var timeout, args;
return function () {
args = arguments;
// 如果 timeout 有值,说明上一次的执行间隔时间还没过
if (!timeout) {
// 进入此 if 说明时间间隔已经过了
// 先执行一次要执行的函数
func.apply(null, args)
// 然后重新设置时间间隔
timeout = setTimeout(function () {
timeout = null;
}, wait);
}
}
}
<input type="text" id="txt">
<script>
var txt = document.getElementById("txt");
// 调用 throttle 函数来将事件处理函数变为一个节流函数
var throttleHandle = throttle(function (event) {
console.log(event.target.value);
}, 1000)
txt.onkeyup = (event) => {
throttleHandle(event);
}
</script>