戻る| setIntervalとsetTimeout |
| setIntervalとsetTimeoutについて |
setInterval
指定した間隔(ミリ秒)ごとにコールバック関数を繰り返し実行するタイマーです。
戻り値 = setInterval(関数, ミリ秒);
| 戻り値 |
タイマーを識別する正の整数の戻り値(ID)を返します。 ※通常は、1から始まる正の整数の値です。 |
| 関数 |
コールバック(繰り返し実行したい)関数を指定します。 関数式やアロー関数など、任意の形式で指定してください。 |
| ミリ秒 |
実行間隔を指定します。 ミリ秒単位で、1秒は1000ミリ秒となります。 |
clearInterval
setIntervalのタイマー処理を停止する関数です。
setIntervalを実行したときに得られる戻り値を使って、タイマーを停止します。
(例)
let intervalID = setInterval(関数, ミリ秒);
setInterval(intervalID);
copy
let count = 0;
console.log("start");
const intervalId = setInteval(()=>
{
count++;
console.log("count:"+count);
if(count === 3)
{
clearInterval(intervalId);
console.log("end");
}
}, 1000);
[実行結果]
start
count:1
count:2
count:3
end
[delay]
指定された関数を繰り返し実行する間隔をミリ秒単位で指定したものとして使用しています。
[イベントループ]
イベントループという仕組みは非同期処理(setIntervalやsetTimeoutなど)を管理し、効率的に実行します。
[タスクキュー]
イベントループはタスクキューと呼ばれる場所を使い、タスクの管理をします。
このタスクキューで実行待ちのコールバック関数を管理します。
[コールスタック]
現在、実行中の関数を管理する場所です。
実行するとコールスタックが空になります。
管理する場所が空になったタイミングで、タスクキューから次のコールバック関数を取り出して、
コールスタックに積んで実行します。
このタスクキューで実行待ちのコールバック関数を管理します。
setIntervalとタスクキュー
指定された間隔でコールバック関数をタスクキューに追加します。
イベントループは、コールスタックが空になると、タスクキューから関数を取り出し、実行します。
このため、指定された間隔で関数が繰り返し、実行されるように見えます。
[注意点]
タイマーの誤差や、コールバック関数の実行時間によって
正確な間隔で実行されない場合があります。
コールバック関数が長い処理を実行するケース
他の処理によって、コールスタックが埋まっているケース
このような場合は、間隔がずれる可能性があります。
setTimeout
指定したミリ秒数だけ時間の経過後に
第1引数に指定した関数を1回だけ実行します。
1秒は1000ミリ秒なので、3000と設定すると3秒後にsetTimeoutに指定した第1引数の関数が実行されます。
setIntervalは指定した時間ごとに繰り返し関数を実行しますが、
setTimeoutは1度のみ実行するという違いがあります。
そのため、setTimeoutを使い、繰り返し指定したい関数を実行する場合は再帰処理などの手法を使う必要があります。
[構文]
setTimeout(関数, delay, arg1, arg2, ... ,arg n);
関数
実行したい関数を指定します。
delay
実行を遅延させる時間をミリ秒単位で指定します。
arg1, arg2, ... ,arg n
関数の引数を指定します(省略可能)
(1)関数を指定する方法
function printLog(text)
{
console.log(text);
}
//2秒後に、printLog関数が実行されます
setTimeout(printlog, 2000, "test");
第1引数のprintLog関数を実行します。
printLog関数には引数が1個、必要としているため第3引数に"test"を設定しています。
第2引数に2000ミリ秒を指定しているので、2秒後にprintLog関数を実行することになります。
(2)無名関数を指定する方法
setTimeout(() => {
console.log("test2");
}, 3000);
無名関数を使用したサンプルです。
3000ミリ秒なので3秒後に無名関数を実行します。
clearTimeout
setIntervalのようにタイマーをキャンセル(停止)することができる方法が用意されています。
setTimeoutはタイマーを識別するための正の整数を返します。
clearTimeout関数を使って、戻り値であるタイマーIDを指定して実行すると
setTimeoutをキャンセル(停止)することができます。
(例)
function cancelTest()
{
console.log("cancelTest");
}
//2秒後にcancelTest関数を実行
const timerId =setTimeout(cancelTest, 2000);
//タイマーをキャンセルするテスト
setTimeout(() => {
clearTimeout(timerId);
console.log("タイマーをキャンセルしました。");
}, 1000);
//3秒後に設定したタイマー処理
setTimeout(() => {
console.log("3秒後に実行したタイマー処理");
}, 3000);
この例では2秒後にcancelTest関数を実行する予定です。
しかし、1秒後に無名関数でclearTimeoutを実行しています。
このclearTimeoutは2秒後に実行する予定のタイマーIDをキャンセルする処理です。
このため、先に実行したclearTimeoutのため2秒後に実行する予定のcancelTestは実行されません。
そして、その後、3秒後に設定したタイマー処理が実行されます。
setTimeoutとsetIntervalの使い分け
setTimeout
特定の時間間隔で一度だけ実行したい場合や、処理の完了後に次の処理を実行したい場合(非同期処理)に適しています。
再帰的に呼び出すことで、setIntervalと同様の繰り返し処理を実装できます。
処理が完了するまで次の処理を実行しないため、処理が遅延しても次の実行に影響を与えません。
setInterval
一定の間隔で定期的に処理を実行したい場合に便利です。
setTimeoutで再帰的に記述するよりもコードがシンプルになる場合があります。
処理が遅延すると、次の実行タイミングがずれてしまう可能性があります。
戻る back| setIntervalとsetTimeout |
| about setIntervalとsetTimeout |
setInterval
A timer that repeatedly executes a callback function at the specified interval (milliseconds).
Return value = setInterval(function, milliseconds);
| Return value |
Returns a positive integer return value (ID) that identifies the timer. *Normally, this is a positive integer value starting from 1. |
| Function |
Specify the callback function (the function you want to execute repeatedly). Specify in any format, such as a function expression or arrow function. |
| Milliseconds |
Specify the execution interval. In milliseconds, 1 function is 1000 milliseconds. |
clearInterval
This is a function that stops the timer processing of setInterval.
The timer is stopped using the return value obtained when executing setInterval.
(Example)
let intervalID = setInterval(function, milliseconds);
copy
let count = 0;
console.log("start");
const intervalId = setInteval(()=>
{
count++;
console.log("count:"+count);
if(count === 3)
{
clearInterval(intervalId);
console.log("end");
}
}, 1000);
[Execution result]
start
count:1
count:2
count:3
end
[delay]
It is used as the interval in milliseconds for repeatedly executing the specified function.
[Event Loop]
The event loop is a mechanism that manages asynchronous processing (such as setInterval and setTimeout) and executes them efficiently.
[Task Queue]
The event loop uses a place called the task queue to manage tasks.
This task queue manages callback functions waiting to be executed.
[Call Stack]
This is where you manage the currently executing functions.
When executed, the call stack will be emptied.
When the area to manage becomes empty, the next callback function is taken from the task queue,
then stacked on the call stack and executed.
This task queue manages the callback functions waiting to be executed.
setInterval and task queue
Adds a callback function to the task queue at the specified interval.
When the call stack becomes empty, the event loop takes the function from the task queue and executes it.
This makes it appear as if the function is being executed repeatedly at the specified interval.
[Notes]
Depending on the timer error and the execution time of the callback function,
it may not be executed at the correct interval.
When the callback function executes a long process
When the call stack is filled by other processes
In such cases, the interval may be off.
setTimeout
After the specified number of milliseconds has elapsed
The function specified in the first argument is executed only once.
Since there are 1000 milliseconds in one second, if you set it to 3000, the function specified in the first argument of setTimeout will be executed after 3 seconds.
The difference is that setInterval executes a function repeatedly at the specified time,
while setTimeout executes only once.
Therefore, if you want to use setTimeout to execute a function you want to specify repeatedly, you need to use a technique such as recursion.
[Syntax]
setTimeout(function, delay, arg1, arg2, ... ,arg n);
function
Specify the function you want to execute.
delay
Specify the time to delay execution in milliseconds.
arg1, arg2, ... ,arg n
Specify function arguments (optional)
(1) How to specify a function
function printLog(text)
{
console.log(text);
}
//After 2 seconds, the printLog function is executed.
setTimeout(printlog, 2000, "test");
Executes the printLog function in the first argument.
The printLog function requires one argument, so the third argument is set to "test".
The second argument is set to 2000 milliseconds, so the printLog function will be executed after 2 seconds.
(2) How to specify an anonymous function
setTimeout(() => {
console.log("test2");
}, 3000);
This is a sample that uses an anonymous function.
The anonymous function will be executed after 3 seconds, since it is 3000 milliseconds.
clearTimeout
Like setInterval, there is a way to cancel (stop) a timer.
setTimeout returns a positive integer to identify the timer.
By using the clearTimeout function and specifying the timer ID, which is the return value,
you can cancel (stop) setTimeout.
(Example)
function cancelTest()
{
console.log("cancelTest");
}
//Execute the cancelTest function after 2 seconds
const timerId =setTimeout(cancelTest, 2000);
//Test to cancel the timer
setTimeout(() => {
clearTimeout(timerId);
console.log("The timer was canceled.");
}, 1000);
//Timer processing set after 3 seconds
setTimeout(() => {
console.log("Timer processing executed after 3 seconds");
}, 3000);
In this example, the cancelTest function is scheduled to run after 2 seconds.
However, after 1 second, an anonymous function executes clearTimeout.
This clearTimeout is a process to cancel the timer ID scheduled to run after 2 seconds.
As a result, cancelTest scheduled to run after 2 seconds will not be executed due to the clearTimeout that was executed first.
Then, the timer process set after 3 seconds will be executed.
How to use setTimeout and setInterval
setTimeout
This is suitable when you want to execute only once at a specific time interval, or when you want to execute the next process after the process is completed (asynchronous processing).
By calling recursively, you can implement a repeating process similar to setInterval.
The next process will not be executed until the process is completed, so even if the process is delayed, it will not affect the next execution.
setInterval
This is useful when you want to execute a process periodically at regular intervals.
This may result in simpler code than writing recursively with setTimeout.
If the process is delayed, the timing of the next execution may be delayed.
back