MENU

JavaScriptで経過時間をリアルタイムで表示するサンプル

サンプルコード

// HTMLが読み込まれた後に以下の処理を読み込む
window.onload = function(){

  function Time_exchange() {
        now_time = new Date();
        sec_present = (now_time.getTime()/1000).toFixed(0);
        // 経過時間の始点
        sec_start = (Date.parse("2021-06-18T08:10:00")/1000).toFixed(0);
        sec_time = sec_present - sec_start;

        // 経過時間の成形
        sec = sec_time % 60;
        time = (sec_time - sec)/60;
        min = time % 60;
        time = (time - min)/60;
        hour = time % 24;
        time = (time - hour)/24;
        days = time;
    // 経過時間表示のデコレーションとviewへの差し込み
    document.getElementById("item").innerHTML =  days + "d " + hour + "h " + min + "m " + sec + "s" ;
  };

  function timer(){
    // 更新頻度の設定
    setInterval(Time_exchange, 1000);
  }
  timer();
}

railsのapplication.jsで読み込んでいるjsの中でHTML要素を読み込む場合はwindow.onloadの中で処理をする

application.jsはheadタグの中で読み込まれてしまうので、HTML要素が上から下まで読み込まれる前に以下のような処理をすると要素を取得できない。

document.getElementById("item").innerHTML

window.onloadの中に処理を書けばこの問題は起こらない。

window.onload = function(){ 処理 }