根据javascript中的字符,在一段时间后执行代码



array=["Rashid","Kalam","NEO"]

拉希德有六个角色,所以它会在6秒后进行游戏。

kalam有5,所以它应该在单词5秒后控制台也是如此

计时器应该一起启动还是一个接一个地启动?

我把它一个接一个地放在这里

let sleep = (ms) => new Promise(res => setTimeout(res,ms));
(async () => {
let array = ["Rashid", "Kalam", "NEO"]
console.log("Start counter now");
for(let item of array) {
let { length } = item;
await sleep(1000 * length);
console.log(item);
}
})()

setTimeout是您的朋友。

let array = ["Rashid", "Kalam", "NEO"];
array.map((name) => setTimeout(()=>console.log(name), name.length * 1000));
['rashid', 'Kalam', 'neo'].forEach(name => setTimeout(() => console.log(name), name.length * 1000))

您可以使用设置间隔函数,然后在数组中添加值,1000ms表示1秒

setInterval(function(){ array = ["Rashid"] }, 6000); 
// use second set interval and add another name or remove. 
setInterval(function(){ array = ["Kalam"] }, 5000);
the 6000 means 6 seconds and 5000 means 5 seconds. 

最新更新