一道简单的JS面试题目(节流)

简单写法

function delayPrint() {
   let callStack = [] // 取错名字了,是队列
   let timer = null
 function print(msg) {
     if (timer) {
       callStack.push(msg);
       return;
     }
     console.log(msg)
     inner()
   }
 function inner() {
     timer = setTimeout(() => {
       timer = null
       // 检查是否还有内容
       if (callStack.length) {
         console.log(callStack.shift())
         inner()
       }
     }, 1000)
   }
   return print
 }
 let dPrint = delayPrint()
 dPrint(1)
 dPrint(2)
 dPrint(3)
 dPrint(4)

写法比较简单,缺点是最后一次执行会停留1s才退出。

然后我拼凑一半天,拼出来一个代码,hhh

function delayPrint() {
   let callStack = []
   let flag = true // 表示是否是可打印的时间范围
   let timer = null
 function print(msg) {
     if (flag) {
       console.log(msg)
       flag = false
        timer = setTimeout(() => {
         flag = true
       }, 1000)
       return;
     }
     callStack.push(msg)
     if (!flag) {
       clearTimeout(timer)
       inner(msg)
     }
   }
 function inner() {
     timer = setTimeout(() => {
       console.log(callStack.shift()); // 输出内容
       // 检查是否还有内容
       if (callStack.length != 0) {
         inner()
       } else {
         flag = true; // 队列清空以后恢复打印范畴
         timer = null
         callStack = [];
       }
     }, 1000)
   }
   return print
 }
 let dPrint = delayPrint()
 dPrint(1)
 dPrint(2)
 dPrint(3)
 dPrint(4)

这下执行到最后一个就会正常退出了。

我代码写的丑,不想误导大家, 贴一个正规军写的

let que = [];
 let time = null;
 function throttle(fn) {
     if (time) {
         que.push(fn);
         return;
     }
     fn();
     time = setTimeout(() => {
         time = null;
         if (que.length) {
             throttle(que.shift());
         }
     }, 1000)
 }
 function print(msg) {
     throttle(() => console.log(msg));
 }
 print(1)
 print(2)
 print(3)

暂无评论

发表评论

您的电子邮件地址不会被公开,必填项已用*标注。

相关推荐