如何在js中延迟遍历不使用settimeout?

2023-06-30 311 0

一个字符串 a = '1234567890'
如何每100毫秒遍历一个1、2、3、4、5...但是不使用settimeout

😎 不使用 setTimeout 那用使用 setInterval 呗!

const str = "1234567890"
let index = 0
let timer = setInterval(() => {
  console.log(str.at(index))
  if(str.length > index) index++
  else clearInterval(timer)
}, 100)
let a = '1234567890'
a.split('').map(item => {
let startTime = new Date().getTime()
while (new Date().getTime() - startTime < 100) {
continue
}
console.log(item)
})

JS 里能相对准确延迟的只有 setTimeout / setInterval 了。

都不能用的话那就还剩个无法精确控制的 requestAnimationFrame。

用 requestAnimationFrame 倒是也能近似实现,自己记录下上次输出时间然后跟当前时间做差值再判断呗,超过 100 毫秒了就输出,没超过就等着下一帧。

不过你这是什么奇奇怪怪的需求……面试题?

P.S. 一个 while 死循环干烧 CPU 倒是也行,估计不是你想要的,整个页面都会卡死。现代浏览器对于这种的甚至会直接判断为异常进程直接杀掉。

使用setInterval

const a = '1234567890';
let index = 0;
const interval = setInterval(() => {
  if (index < a.length) {
    console.log(a[index]);
    index++;
  } else {
    clearInterval(interval);
  }
}, 100);

或者用requestAnimationFrame, 不过这个误差会大

  const a = '1234567890';
  let index = 0;
  let startTime = null;
  function step (timestamp) {
    if (!startTime) startTime = timestamp;
    const elapsed = timestamp - startTime;
    if (elapsed >= 100) {
      console.log(a[index]);
      index++;
      startTime = null;
    }
    if (index < a.length) {
      requestAnimationFrame(step);
    }
  }
  requestAnimationFrame(step);
  function main(a) {
if (!a) return
let startTime = performance.now()
while (performance.now() - startTime < 100) {}
console.log(a.charAt(0))
main(a.slice(1))
}
main("1234567890")

回答

相关文章

nuxt2部署静态化和ssr的时候访问首页先报404再出现首页为什么?
`clip-path` 如何绘制圆角平行四边形呢?
多线程wait方法报错?
VUE 绑定的方法如何直接使用外部函数?
vue2固定定位该怎么做?
谁有redis实现信号量的代码,希望借鉴一下?