日常代碼邏輯實現:
1.防抖
解釋:
- 防抖是指n秒內只執行一次,如果n秒內事件再次觸發,則重新計算時間
應用場景:
- 搜索框輸入聯想(避免每次按鍵都發送請求)
- 窗口尺寸調整
代碼實現:
// 第一種實現方式:定時器
const debounce = (func, delay) => {let timer = null;return function () {const _this = this;const args = arguments;//如果存在則先清楚定時器if (timer) {clearTimeout(timer);}timer = setTimeout(() => {func.apply(_this, args);//重置狀態timer = null;}, delay);};
};
2.節流
解釋:
- 節流是指n秒內只執行一次,只有等上一次觸發事件執行完畢才會執行下一次
應用場景:
- 鼠標滾動事件
- 表單提交
代碼實現:
// 第一種實現方式:定時器
const throttle1 = (func, delay) => {let temp = false;return function () {const _this = this;const args = arguments;if (temp) return;temp = true;setTimeout(() => {func.apply(_this, args);temp = false;}, delay);};
};// 第二種實現方式:時間戳
const throttle2 = (func, wait) => {let lastTime = 0;return function () {const _this = this;const args = arguments;const now = Data.now();if (now - lastTime >= wait) {func(_this, args);lastTime = now;}};
};
3.紅綠黃燈交替亮
解釋:
- 紅燈亮3秒,接著綠燈亮2秒,然后黃燈亮1秒后再亮紅燈,以此重復
代碼實現如下:
使用promise和async/await來實現
// 紅綠燈交替重復亮
const redGreenLight = (current, delay, next) => {return new Promise(resolve => {setTimeout(() => {console.log(`當前是${current}燈,${delay}秒后變成${next}燈`);}, delay * 1000);});
};const test = async () => {while (true) {await redGreenLight("紅", 3, "綠");await redGreenLight("綠", 2, "黃");await redGreenLight("黃", 1, "紅");}
};