事件防抖:在用户连续触发事件过程中,不能执行代码。
//防抖debounce代码:function debounce(fn) {let timeout = null; // 创建一个标记用来存放定时器的返回值return function () {// 每当用户输入的时候把前一个 setTimeout clear 掉clearTimeout(timeout);// 然后又创建一个新的 setTimeout,//这样就能保证interval 间隔内如果时间持续触发,就不会执行 fn 函数timeout = setTimeout(() => {fn.apply(this, arguments);}, 500);};}// 处理函数function handle() {console.log(Math.random());}// 滚动事件window.addEventListener('scroll', debounce(handle));
事件节流:设置一个时间间隔,时间间隔内只允许执行一次。
//节流throttle代码:function throttle(fn) {let canRun = true; // 通过闭包保存一个标记return function () {// 在函数开头判断标记是否为true,不为true则returnif (!canRun) return;// 立即设置为falsecanRun = false;// 将外部传入的函数的执行放在setTimeout中setTimeout(() => {// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。// 当定时器没有执行的时候标记永远是false,在开头被return掉fn.apply(this, arguments);canRun = true;}, 500);};}function sayHi(e) {console.log(e.target.innerWidth, e.target.innerHeight);}window.addEventListener('resize', throttle(sayHi));
