カウントダウンタイマーを作成するJavaScriptプログラム

Javascript

例:カウントダウンタイマーを作成する

// program to create a countdown timer

// time to countdown from (in milliseconds)
let countDownDate = new Date().getTime() + 24 * 60 * 60 * 1000;

// countdown timer
let x = setInterval(function() {

    // get today's date and time in milliseconds
    let now = new Date().getTime();

    // find the interval between now and the countdown time
    let timeLeft = countDownDate - now;

    // time calculations for days, hours, minutes and seconds
    const days = Math.floor( timeLeft/(1000*60*60*24) );
    const hours = Math.floor( (timeLeft/(1000*60*60)) % 24 );
    const minutes = Math.floor( (timeLeft/1000/60) % 60 );
    const seconds = Math.floor( (timeLeft/1000) % 60 );

    // display the result in the element with id="demo"
    console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");

    // clearing countdown when complete
    if (timeLeft < 0) {
        clearInterval(x);
        console.log('CountDown Finished');
    }
    }, 2000);

出力

0d 23h 59m 57s 
0d 23h 59m 55s 
0d 23h 59m 53s 
0d 23h 59m 51s 
...

上記のプログラムでは、 setInterval() メソッドはタイマーを作成するために使用されます。

ザ・ setInterval() メソッドは指定された間隔で実行されます(ここでは、 2000 ミリ秒)。

ザ・ new Date() 現在の日付と時刻を示します。 例えば、

let d1 = new Date();
console.log(time); // Fri Aug 28 2020 09:19:40 GMT+0545 (+0545)

ザ・ getTime() メソッドは、の午前0時からのミリ秒数を返します。 1970年1月1日(EcmaScriptエポック) 指定された日付(ここでは、現在の日付)まで。

次のコードは、翌日の時刻をミリ秒単位で示しています。

new Date().getTime() + 24 * 60 * 60 * 1000;

これで、次の式を使用して残り時間を計算できます。

let timeLeft = countDownDate - now;

残りの日数は、以下を使用して計算されます。

  • 時間間隔はで除算されます 1000 秒数を決定する、すなわち timeLeft / 1000
  • 次に、時間間隔をで除算します。 60 * 60 * 24 残りの日数を決定します。
  • ザ・ Math.floor() 関数は、数値を整数に丸めるために使用されます。

同様の方法が、時間、分、および秒に使用されます。


注意:特定の日付を渡すことで、カスタムの開始カウントダウン時間を使用することもできます。

例えば、

let countDownDate = new Date("Aug 5, 2025 14:22:36").getTime();



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です