iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 26
0
Modern Web

從Stack Overflow學前端系列 第 26

從StackOverflow上學CODING(26) setTimeout或 setInterval?

setTimeout or setInterval?

As far as I can tell, these two pieces of javascript behave the same way:
據我所知:這兩個方式好像是做一樣的事情?

Option A:

function myTimeoutFunction()
{
    doStuff();
    setTimeout(myTimeoutFunction, 1000);
}

myTimeoutFunction();

Option B:

function myTimeoutFunction()
{
    doStuff();
}

myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);

They essentially try to do the same thing, but the setInterval approach will be more accurate than the setTimeout approach, since setTimeout waits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms (or a lot more if your function takes a long time to execute).

他們原則是是在做一樣的事情,但是setInterval方法會比較精準,setTimeout會等待1000ns然後再跑函式然後再設一個Timeout,所以等待的其間其實比1000ms還多一些(如果你的函示很大會跑很久才執行完成則可能有更大的誤差)

Altough one might think that setInterval will execute exactly every 1000ms, it is important to note that setInterval will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish.

到這裡你可能會覺得那setInterval則可能會精準地在每1000ms時執行,但其實setInterval也是會延遲,因為JS是多線呈執行的語言,也就是說它會等待其他script執行後interval才會再執行

In this Fiddle, you can clearly see that the timeout will fall behind, while the interval is almost all the time at almost 1 call/second (which the script is trying to do). If you change the speed variable at the top to something small like 20 (meaning it will try to run 50 times per second), the interval will never quite reach an average of 50 iterations per second.

在這個例子,你可以清楚地看到timeout會落後,而interval則很接近每一秒執行一次,如果你改變變數的速度,例如像20(意味著它會嘗試每秒跑50次),interval會永遠都沒辦法跑得很接近每秒50次

The delay is almost always negligible, but if you're programming something really precise, you should go for a self-adjusting timer (which essentially is a timeout-based timer that constantly adjusts itself for the delay it's created)

這個延遲幾乎是可以忽視的,但是如果你在設計某些東西需要非常精準,你最好設一個會自我調節時間的功能


上一篇
從StackOverflow上學CODING(25) 甚麼時候用 call()& apply()& bind()
下一篇
從StackOverflow上學CODING(27) JS return多個值
系列文
從Stack Overflow學前端30

尚未有邦友留言

立即登入留言