一个字符串 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")