setTimeout 또는 setInterval?
내가 알 수있는 한,이 두 가지 자바 스크립트는 동일한 방식으로 작동합니다.
옵션 A :
function myTimeoutFunction()
{
doStuff();
setTimeout(myTimeoutFunction, 1000);
}
myTimeoutFunction();
옵션 B :
function myTimeoutFunction()
{
doStuff();
}
myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);
setTimeout 과 setInterval을 사용하는 데 차이가 있습니까?
그들은 본질적으로 동일한 작업을 시도하지만 setInterval
접근 방식은 1000ms를 기다렸다가 함수를 실행 한 다음 다른 시간 제한을 설정하기 setTimeout
때문에 접근 방식 보다 더 정확 setTimeout
합니다. 따라서 대기 시간은 실제로 1000ms 이상입니다 (또는 함수를 실행하는 데 오랜 시간이 걸리는 경우 훨씬 더 많이).
이것이 정확히 1000ms마다 setInterval
실행될 것이라고 생각할 수도 있지만 JavaScript는 다중 스레드 언어가 아니기 때문에 지연 될 수도 있습니다. 즉, 스크립트의 다른 부분이 실행중인 경우 간격이 완료 될 때까지 기다립니다.setInterval
에서 이 바이올린 , 당신은 명확 간격이 (스크립트가 시도됩니다) 둘째 거의 1 전화 /에 거의 모든 시간 동안 타임 아웃이 뒤 떨어질 것을 볼 수 있습니다. 상단의 속도 변수를 20과 같은 작은 값으로 변경하면 (초당 50 회 실행을 시도 함을 의미) 간격은 초당 평균 50 회 반복에 도달하지 않습니다.
지연은 거의 항상 무시할 수 있지만 정말 정확한 것을 프로그래밍하는 경우 자체 조정 타이머 를 사용해야합니다 (기본적으로 생성되는 지연에 대해 지속적으로 자체 조정하는 시간 제한 기반 타이머).
차이가 있습니까?
예. Timeout은 setTimeout ()이 호출 된 후 일정 시간 동안 실행됩니다. Interval은 이전 간격이 실행 된 후 일정 시간 동안 실행됩니다.
doStuff () 함수를 실행하는 데 시간이 걸리면 차이를 알 수 있습니다. 예를 들어를 사용하여 setTimeout / setInterval에 대한 호출 .
,를 사용하여 시간 초과 / 간격을 *
실행하고 [-----]
를 사용하여 JavaScript 코드를 실행하는 경우 타임 라인은 다음과 같습니다.
Timeout:
. * . * . * . * .
[--] [--] [--] [--]
Interval:
. * * * * * *
[--] [--] [--] [--] [--] [--]
다음 문제는 자바 스크립트가 이미 무언가를하는 동안 (이전 간격 처리와 같은) 간격이 발생하는 경우입니다. 이 경우 간격이 기억되고 이전 처리기가 완료되고 브라우저에 제어가 반환되는 즉시 발생합니다. 예를 들어, 때로는 짧고 ([-]) 때로는 긴 ([-----]) doStuff () 프로세스의 경우 :
. * * • * • * *
[-] [-----][-][-----][-][-] [-]
• 코드를 바로 실행할 수없고 대신 보류 상태가 된 간격 발생을 나타냅니다.
그래서 인터벌은 일정대로 돌아 가기 위해 '추격'하려고합니다. 그러나 그들은 서로의 위에 하나를 큐에 넣지 않습니다. 간격 당 하나의 실행 만 보류 될 수 있습니다. (모두 대기열에 있으면 브라우저에 계속해서 확장되는 미해결 실행 목록이 남습니다!)
. * • • x • • x
[------][------][------][------]
x는 실행할 수 없거나 보류 상태로 만들 수있는 간격 발생을 나타내므로 대신 삭제되었습니다.
doStuff () 함수가 설정된 간격보다 실행하는 데 습관적으로 더 오래 걸리는 경우 브라우저는 서비스를 위해 CPU를 100 % 소모하여 응답 성이 떨어질 수 있습니다.
어떤 것을 사용하고 왜 사용합니까?
Chained-Timeout은 브라우저에 보장 된 자유 시간 슬롯을 제공합니다. Interval은 브라우저 UI 가용성을 희생하면서 실행중인 함수가 예약 된 시간에 최대한 가깝게 실행되도록합니다.
가능한 한 매끄럽게하고 싶었던 일회성 애니메이션의 간격을 고려하고, 페이지가로드되는 동안 항상 발생하는 진행중인 애니메이션에는 체인 타임 아웃이 더 정중합니다. 덜 까다로운 용도 (예 : 30 초마다 실행되는 사소한 업데이트 프로그램)의 경우 둘 중 하나를 안전하게 사용할 수 있습니다.
브라우저 호환성 측면에서 setTimeout은 setInterval보다 이전이지만 오늘 만나게 될 모든 브라우저는 둘 다 지원합니다. 수년 동안 마지막으로 어려움을 겪은 것은 WinMo <6.5의 IE Mobile 이었지만 이제는 그것도 우리 뒤에 있습니다.
setInterval ()
setInterval()
간격에 도달했을 때 지정된 스크립트를 반복적으로 실행할 수있는 기본 기능이있는 시간 간격 기반 코드 실행 방법입니다. 해야 하지 가 있기 때문에,이 루프를 만들기 위해 스크립트 작성자의 콜백 함수에 중첩 될 수 기본적으로 루프 . 전화하지 않는 한 간격으로 계속 발사됩니다 clearInterval()
.
애니메이션 또는 시계 틱에 대한 코드를 반복하려면 setInterval()
.
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);
setTimeout ()
setTimeout()
간격에 도달했을 때 스크립트를 한 번만 실행하는 시간 기반 코드 실행 방법입니다 . 그것은 것입니다 하지 당신이 중첩에 의해 루프 스크립트를, 기어 않는 한 다시 반복 setTimeout()
그것을 실행 호출 함수의 객체의 내부. 루프를 설정하면를 호출하지 않는 한 간격으로 계속 발사됩니다 clearTimeout()
.
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);
지정된 시간 후에 한 번만 발생하려면을 사용하십시오 setTimeout()
. 지정된 간격에 도달하면 한 번만 실행되기 때문입니다.
setInterval을 사용하면 향후 코드 실행을 더 쉽게 취소 할 수 있습니다. setTimeout을 사용하는 경우 나중에 취소하려는 경우 타이머 ID를 추적해야합니다.
var timerId = null;
function myTimeoutFunction()
{
doStuff();
timerId = setTimeout(myTimeoutFunction, 1000);
}
myTimeoutFunction();
// later on...
clearTimeout(timerId);
대
function myTimeoutFunction()
{
doStuff();
}
myTimeoutFunction();
var timerId = setInterval(myTimeoutFunction, 1000);
// later on...
clearInterval(timerId);
setTimeout
시간 제한을 취소 하려면 방법을 사용하기가 더 쉽습니다.
function myTimeoutFunction() {
doStuff();
if (stillrunning) {
setTimeout(myTimeoutFunction, 1000);
}
}
myTimeoutFunction();
Also, if something would go wrong in the function it will just stop repeating at the first time error, instead of repeating the error every second.
The very difference is in their purposes.
setInterval()
-> executes a function, over and over again, at specified time intervals
setTimeout()
-> executes a function, once, after waiting a specified number of milliseconds
It's as simple as that
More elaborate details here http://javascript.info/tutorial/settimeout-setinterval
When you run some function inside setInterval, which works more time than timeout-> the browser will be stuck.
- E.g., doStuff() takes 1500 sec. to be execute and you do: setInterval(doStuff, 1000);
1) Browser run doStuff() which takes 1.5 sec. to be executed;
2) After ~1 second it tries to run doStuff() again. But previous doStuff() is still executed-> so browser adds this run to the queue (to run after first is done).
3,4,..) The same adding to the queue of execution for next iterations, but doStuff() from previous are still in progress...
As the result- the browser is stuck.
To prevent this behavior, the best way is to run setTimeout inside setTimeout to emulate setInterval.
To correct timeouts between setTimeout calls, you can use self-correcting alternative to JavaScript's setInterval technique.
I use setTimeout.
Apparently the difference is setTimeout calls the method once, setInterval calls it repeatdly.
Here is a good article explaining the difference: Tutorial: JavaScript timers with setTimeout and setInterval
I've made simple test of setInterval(func, milisec)
, because I was curious what happens when function time consumption is greater than interval duration.
setInterval
will generally schedule next iteration just after the start of the previous iteration, unless the function is still ongoing. If so, setInterval
will wait, till the function ends. As soon as it happens, the function is immediately fired again - there is no waiting for next iteration according to schedule (as it would be under conditions without time exceeded function). There is also no situation with parallel iterations running.
I've tested this on Chrome v23. I hope it is deterministic implementation across all modern browsers.
window.setInterval(function(start) {
console.log('fired: ' + (new Date().getTime() - start));
wait();
}, 1000, new Date().getTime());
Console output:
fired: 1000 + ~2500 ajax call -.
fired: 3522 <------------------'
fired: 6032
fired: 8540
fired: 11048
The wait
function is just a thread blocking helper - synchronous ajax call which takes exactly 2500 milliseconds of processing at the server side:
function wait() {
$.ajax({
url: "...",
async: false
});
}
Your code will have different execution intevals, and in some projects, such as online games it's not acceptable. First, what should you do, to make your code work with same intevals, you should change "myTimeoutFunction" to this:
function myTimeoutFunction()
{
setTimeout(myTimeoutFunction, 1000);
doStuff();
}
myTimeoutFunction()
After this change, it will be equal to
function myTimeoutFunction()
{
doStuff();
}
myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);
But, you will still have not stable result, because JS is single-threaded. For now, if JS thread will be busy with something, it will not be able to execute your callback function, and execution will be postponed for 2-3 msec. Is you have 60 executions per second, and each time you have random 1-3 sec delay, it will be absolutely not acceptable (after one minute it will be around 7200 msec delay), and I can advice to use something like this:
function Timer(clb, timeout) {
this.clb = clb;
this.timeout = timeout;
this.stopTimeout = null;
this.precision = -1;
}
Timer.prototype.start = function() {
var me = this;
var now = new Date();
if(me.precision === -1) {
me.precision = now.getTime();
}
me.stopTimeout = setTimeout(function(){
me.start()
}, me.precision - now.getTime() + me.timeout);
me.precision += me.timeout;
me.clb();
};
Timer.prototype.stop = function() {
clearTimeout(this.stopTimeout);
this.precision = -1;
};
function myTimeoutFunction()
{
doStuff();
}
var timer = new Timer(myTimeoutFunction, 1000);
timer.start();
This code will guarantee stable execution period. Even thread will be busy, and your code will be executed after 1005 mseconds, next time it will have timeout for 995 msec, and result will be stable.
To look at it a bit differently: setInterval insures that a code is run at every given interval (i.e. 1000ms, or how much you specify) while setTimeout sets the time that it 'waits until' it runs the code. And since it takes extra milliseconds to run the code, it adds up to 1000ms and thus, setTimeout runs again at inexact times (over 1000ms).
For example, timers/countdowns are not done with setTimeout, they are done with setInterval, to ensure it does not delay and the code runs at the exact given interval.
Both setInterval and setTimeout return a timer id that you can use to cancel the execution, that is, before the timeouts are triggered. To cancel you call either clearInterval or clearTimeout like this:
var timeoutId = setTimeout(someFunction, 1000);
clearTimeout(timeoutId);
var intervalId = setInterval(someFunction, 1000),
clearInterval(intervalId);
Also, the timeouts are automatically cancelled when you leave the page or close the browser window.
Well, setTimeout is better in one situation, as I have just learned. I always use setInterval, which i have left to run in the background for more than half an hour. When i switched back to that tab, the slideshow (on which the code was used) was changing very rapidly, instead of every 5 seconds that it should have. It does in fact happen again as i test it more and whether it's the browser's fault or not isn't important, because with setTimeout that situation is completely impossible.
You can validate bobince answer by yourself when you run the following javascript or check this JSFiddle
<div id="timeout"></div>
<div id="interval"></div>
var timeout = 0;
var interval = 0;
function doTimeout(){
$('#timeout').html(timeout);
timeout++;
setTimeout(doTimeout, 1);
}
function doInterval(){
$('#interval').html(interval);
interval++;
}
$(function(){
doTimeout();
doInterval();
setInterval(doInterval, 1);
});
The difference is obvious in console:
Just adding onto what has already been said but the setTimeout version of the code will also reach the Maximum call stack size
which will stop it from functioning. Since there is no base case for the recursive function to stop at so you can't have it run forever.
I think SetInterval
and SetTimeout
are different. SetInterval
executes the block according to the time set while, SetTimeout
executes the block of code once.
Try these set of codes after the timeout countdown seconds:
setInterval(function(e){
alert('Ugbana Kelvin');
}, 2000);
and then try
setTimeout(function(e){
alert('Ugbana Kelvin');
}, 2000);
You can see the differences for yourself.
참고URL : https://stackoverflow.com/questions/729921/settimeout-or-setinterval
'Nice programing' 카테고리의 다른 글
난수 생성기는 하나의 난수 만 생성 (0) | 2020.09.29 |
---|---|
hr 요소의 색상 변경 (0) | 2020.09.29 |
JavaScript에서 문자열을 Base64로 어떻게 인코딩 할 수 있습니까? (0) | 2020.09.29 |
Git에서 단일 브랜치를 어떻게 복제합니까? (0) | 2020.09.29 |
C #에서 문자를 반복하는 가장 좋은 방법 (0) | 2020.09.29 |