[英]How can i print number in regular interval through setTimeout function?
var i=0;
function counter(){
for( i;i<100;i++){
setTimeout(()=>{
console.log(i);
},2000)
}
}
counter();
我想以 2 秒的間隔打印 i 但它立即打印
每次打印調用只需幾微秒。 為什么? 因為它只是調用 setTimeout。 執行 setTimeout 只需幾微秒即可完成。 電話所做的只是安排將來要發生的事情。 所以在幾微秒內,你已經安排了 10 件事在未來大約 2 秒內發生。 所有的調度幾乎同時發生。 因此,所有控制台日志大約在您安排它們后兩秒鍾的同一時間發生。
如何使用 for 循環以 2 秒的間隔打印?
1
2
3
4
...在 2 秒延遲通過 for 循環
const printNumbersForEvery2Sec = (n) => { for (let i = 1; i <= n; i++) { setTimeout(() => { console.log(i) }, i * 2000) } } printNumbersForEvery2Sec(10);
取自這里
使用setInterval() ,像這樣:
var i=0; var intervalID; function printAndIncrement() { // Stop interval procedure when "var i" reach to 100. if (i > 100) { clearInterval(intervalID); return; } console.log(i); i++; } intervalID = setInterval(printAndIncrement, 1000);
如何以 2 秒的間隔打印?
由於 CPU 時間導致的“漂移”是一個考慮因素。
如果您的用例運行的代碼間隔至少為2 秒,請使用setTimeout()
:
let ctr = 1 const fn = () => { console.log(ctr++) setTimeout(fn, 2000) // set the next run } setTimeout(fn, 2000) // set 1st run
如果您的用例運行的代碼間隔最大為2 秒,請使用setInterval()
:
let ctr = 1 const fn = () => console.log(ctr++) setInterval(fn, 2000)
有關 JS CPU 計時器漂移的更多信息,請訪問: https : //johnresig.com/blog/how-javascript-timers-work/
干杯,
function counter(){
for( let i=0;i<100;i++){
setTimeout(()=>{
console.log(i);
},2000)
}
}counter();
只需更改var
即可let
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.