函数防抖(debounce):
当持续触发事件时,一定事件段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
“函数防抖”的关键在于:在一个动作发生一定事件之后,才执行特定的事件。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><style>#content {width: 200px;height: 200px;background-color: gray;margin: 100px;color: black;padding: 50px;font-size: 56px;}</style></head><body><div id="content"></div><script>var num = 0;var content = document.getElementById("content");var changeNum = function(){num++;content.innerHTML = num;}var debounce = function(func, delay){var timer;return function(...args){if (timer) {clearTimeout(timer);}// 第一版// timer = setTimeout(function(){// // timeout的this是window,但实际上应该是content元素// func();// }, delay);// 第二版,使用箭头函数的特性// 箭头函数没有this作用域,他的this来自作用域链,也没有argumentstimer = setTimeout(() => {console.log(this);func(...args);}, delay);};};content.onmouseover = debounce(changeNum, 500);</script></body></html>
函数节流(throttle):
当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title></head><body><button id="btn1">点击</button><script>let btn1 = document.getElementById('btn1');let fn = () => {console.log('我被点击了');};let throttle = function(func, delay) {var flag = true;return function(...args){if(!flag) {return;}flag = false;setTimeout(()=>{func(args);flag = true;},delay);};};btn1.onclick = throttle(fn, 2000);</script></body></html>
有可以使用时间戳来实现。
