【JavaScript】時間になったら実行されるプログラムの作り方とサンプル
WEBサイトの中には5秒後に処理したい、イベント日までをカウントして表示したいなど、特定の時間までカウントしたいということがよくあります。
今回の記事では指定した時間までをカウントし、その時間になったら処理を実行するプログラムをご紹介します。
この記事の目次を表示
時間になったら処理が実行されるプログラムの作り方とサンプル
完成例
まずは時間になったら処理が実行されるプログラムの完成例をご紹介します。
<div id="countdown"></div>
let count = 100; // 秒数指定
let countdownInterval = setInterval(countdown, 1000);
// カウントダウン関数
function countdown() {
document.getElementById('countdown').innerHTML = count--;
if (count < 0) {
clearInterval(countdownInterval);
endFunction();
}
}
// 0になった時の関数
function endFunction() {
document.getElementById('countdown').innerHTML = 'END';
}
See the Pen Untitled by 寺井大樹 (@teraisan) on CodePen.
こちらの例では1秒ごとにカウントを減らし、0になったタイミングでENDと表示します。
プログラムの解説
まず初めにカウントする秒数は以下に指定します。
let count = 100; // 秒数指定
続いて、setInterval関数を使用して繰り返したい関数を1秒ごとに実行するように設定します。
let countdownInterval = setInterval(countdown, 1000);
setInterval関数で指定した1秒ごとに繰り返したい関数は以下となります。
// カウントダウン関数
function countdown() {
document.getElementById('countdown').innerHTML = count--;
if (count < 0) {
clearInterval(countdownInterval);
endFunction();
}
}
この関数は変数count
が0じゃなければ、値を1減らします。変数count
が0の時はsetInterval関数
を止め、endFunction関数
を実行します。
// 0になった時の関数
function endFunction() {
document.getElementById('countdown').innerHTML = 'END';
}
ここにカウントが0になった際の処理を指定します。
上の例ではカウントが0になったら、「END」と表示されるようになっています。
よくある例としてはカウントが0になったタイミングで特定の要素を表示したり、削除したり、リダイレクトしたりなどです。
特定の要素を表示する場合は以下のような関数を使用します。
// 0になった時の関数
function endFunction() {
let element = document.getElementById('●●●●●●');
if (element) {
element.style.display = 'block';
}
}
特定の要素を削除する場合は以下のような関数を使用します。
// 0になった時の関数
function endFunction() {
let element = document.getElementById('●●●●●●');
if (element) {
element.parentNode.removeChild(element);
}
}
特定ページへリダイレクトする場合は以下のような関数を使用します。
// 0になった時の関数
function endFunction() {
// リダイレクト先のURLを設定
let redirectURL = '●●●●●●';
// リダイレクト実行
window.location.href = redirectURL;
}
いろいろな時間を設定してみる
上の例では秒数を指定して、カウントを1秒ずつ減らしていきましたが、その他の例として、日時を指定してその時間になったら処理が実行されるプログラムを2パターンご紹介したいと思います。
明日の0時を設定
以下の例では明日の0時を処理のタイミングとして設定することが可能です。
<div id="countdown"></div>
let targetDate = new Date(); // 現在の日時を取得
targetDate.setDate(targetDate.getDate()+1); // 明日に設定
targetDate.setHours(0, 0, 0, 0); // 0時に設定
let totalSeconds = calculateRemainingSeconds(targetDate);
let count = totalSeconds;
let countdownInterval = setInterval(countdown, 1000);
// カウントダウン関数
function countdown() {
let hours = Math.floor(count / 3600);
let minutes = Math.floor((count % 3600) / 60);
let seconds = count % 60;
let formattedTime = formatTime(hours) + ":" + formatTime(minutes) + ":" + formatTime(seconds);
document.getElementById('countdown').innerHTML = formattedTime;
if (count <= 0) {
clearInterval(countdownInterval);
endFunction();
} else {
count--;
}
}
// 0になった時の関数
function endFunction() {
document.getElementById('countdown').innerHTML = 'END';
}
// 明日の0時までの残り秒数を計算する関数
function calculateRemainingSeconds(targetDate) {
let now = new Date();
let tomorrow = new Date(targetDate);
tomorrow.setDate(tomorrow.getDate());
tomorrow.setHours(0, 0, 0, 0);
let remainingSeconds = Math.floor((tomorrow - now) / 1000);
return remainingSeconds > 0 ? remainingSeconds : 0;
}
// 1桁の場合0を付ける関数
function formatTime(time) {
return time < 10 ? "0" + time : time;
}
See the Pen Untitled by 寺井大樹 (@teraisan) on CodePen.
任意の日時を設定
以下の例では任意の日時を処理のタイミングとして設定することが可能です。
<div id="countdown"></div>
// 指定したい日付をセット(例: 2025年1月1日の0時)
let targetDate = new Date("2025-01-01T00:00:00");
let totalSeconds = calculateRemainingSeconds(targetDate);
let count = totalSeconds;
let countdownInterval = setInterval(countdown, 1000);
// カウントダウン関数
function countdown() {
let days = Math.floor(count / (3600 * 24));
let hours = Math.floor((count % (3600 * 24)) / 3600);
let minutes = Math.floor((count % 3600) / 60);
let seconds = count % 60;
let formattedTime = formatTime(days) + "日 " + formatTime(hours) + ":" + formatTime(minutes) + ":" + formatTime(seconds);
document.getElementById('countdown').innerHTML = formattedTime;
if (count <= 0) {
clearInterval(countdownInterval);
endFunction();
} else {
count--;
}
}
// 0になった時の関数
function endFunction() {
document.getElementById('countdown').innerHTML = 'END';
}
// 明日の0時までの残り秒数を計算する関数
function calculateRemainingSeconds(targetDate) {
let now = new Date();
let tomorrow = new Date(targetDate);
tomorrow.setDate(tomorrow.getDate());
tomorrow.setHours(0, 0, 0, 0);
let remainingSeconds = Math.floor((tomorrow - now) / 1000);
return remainingSeconds > 0 ? remainingSeconds : 0;
}
// 1桁の場合0を付ける関数
function formatTime(time) {
return time < 10 ? "0" + time : time;
}
See the Pen Untitled by 寺井大樹 (@teraisan) on CodePen.
以下の部分に指定したい日時を記載します。
let targetDate = new Date("2025-01-01T00:00:00");
まとめ
いかがでしたか?
今回の記事ではJavaScriptを使用して特定の時間までのカウントダウンを行い、その時間になったら特定の処理を実行する機能をご紹介しました。
この仕組みを使えば、ウェブページ上で時間制約のあるイベントやアクションを管理することが可能ですね。
お好みに合わせて機能を追加・変更し、ユーザーにとって便利な機能を提供できるよう工夫してみてください。JavaScriptの力を借りて、時間とイベントを上手に扱い、より魅力的なウェブページを構築しましょう。