防抖与节流实现
函數防抖
規定間隔不超過n毫秒的連續調用內只有一次調用生效。
function debounce(func, wait) {let timeId;return function(...args) {let _this = this;clearTimeout(timeId);timeId = setTimeout(function() {func.apply(_this, args);}, wait);} }函數節流
規定n秒內函數只有一次調用生效。
function throttle(func, wait) {let lastTime, deferTimer;return function(...args) {let _this = this;let currentTime = Date.now();if (!lastTime || currentTime >= lastTime + wait) {lastTime = currentTime;func.apply(_this, args);} else {clearTimeout(deferTimer);deferTimer = setTimeout(function() {lastTime = currentTime;func.apply(_this, args);}, wait);}} }總結
- 上一篇: js实现千分位分割
- 下一篇: Promise、Promise.all和