日常代码逻辑实现:
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, "红");}
};