函数的防抖和节流
防抖
所謂防抖,就是指觸發事件后在n秒內函數只能觸發一次,如果在n秒內又觸發了事件,則會重新計算函數執行時間。
/*防抖函數@param {Function} func 要執行的函數@param {Number} wait 要等待的時間 ms */ function debounce(func, wait) {let timer = null;return function () {let context = this;let args = arguments;timer && clearTimeout(timer);timer = setTimeout(() => {func.apply(context, args)}, wait);} }// 使用方法 document.getElementById('btn').onclick = debounce(function () { this.innerHTML = '按鈕' + num++; }, 200);
?
節流
所謂節流,就是指連續觸發事件,但是在n秒中只執行一次函數。
/*節流函數@param {Function} func 要執行的函數@param {Number} wait 要等待的時間 ms */ function throttle(func, wait) {// 記錄上一次函數觸發的時間let lastTime = 0;return function () {let nowTime = Date.now();let context = this;let args = arguments;if (nowTime - lastTime > wait) {// 修正this指向 func.apply(context, args);lastTime = nowTime;}} };// 使用方法 document.onmousemove = throttle(function () {console.log('函數觸發了?') }, 200);
?
轉載于:https://www.cnblogs.com/z937741304/p/11468621.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
- 上一篇: vu项目中按F5刷新element菜单没
- 下一篇: VS Code 配置 Python 开发