1

I'm trying to display the time on a clock that I created on my website, so I used the setInterval to display the time every seconds. But it only runs once and I don't know what to do. However, Firefox doesn't notice any error in my code.

var date = new Date(); //Time of the clock in-game
var hours;
var minutes;
var seconds;

var display_hours; // Displayers for the time
var display_minutes;
var display_seconds;

window.onload = function() {
    display_hours = document.getElementById("hour");
    display_minutes = document.getElementById("minute");
    display_seconds = document.getElementById("second");
};

function time_on() {
    hours = date.getHours();
    if (hours < 10) {
        hours = "0" + hours;
    };
    minutes = date.getMinutes();
    if (minutes < 10) {
        minutes = "0" + minutes;
    };
    seconds = date.getSeconds();
    if (seconds < 10) {
        seconds = "0" + seconds;
    };

    display_hours.textContent = hours;
    display_minutes.textContent = minutes;
    display_seconds.textContent = seconds;
};

var go_time = setInterval(time_on, 1000); // Display time on the clock every seconds

I want to be able to clear this interval later in the code.

Alex
  • 81
  • 1
  • 2
  • 12

2 Answers2

0

My guess is that window.onload triggers after you already created the interval, so inside the interval handler, display_{hours,minutes,seconds} are undefined and cause your code to crash.

Try starting the interval from within the onload handler:

window.onload = function() {
    display_hours = document.getElementById("hour");
    display_minutes = document.getElementById("minute");
    display_seconds = document.getElementById("second");
    var go_time = setInterval(time_on, 1000);
};

EDIT: also, make sure you actually update date each time:

function time_on() {
  date = new Date();
  ...
}
robertklep
  • 198,204
  • 35
  • 394
  • 381
0

This is a simple clock:

function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
return i;
}

and in the body put this:

<body onload="startTime()">
Matteo Pagani
  • 545
  • 5
  • 14