Search code examples
javascriptoopobject-literal

Making my LiveTime object literal


This is the code I used to have, which worked fine:

var todayTime = new Date();
(function updateClock() {
    todayTime.setTime(todayTime.valueOf() + 1000);

    // In 2 digit format.
    document.getElementById("hours").innerHTML   = ("0" + todayTime.getHours()).slice(-2);
    document.getElementById("minutes").innerHTML = ("0" + todayTime.getMinutes()).slice(-2);
    document.getElementById("seconds").innerHTML = ("0" + todayTime.getSeconds()).slice(-2);

    setTimeout(updateClock, 1000);
})();

I attempted to changed it to an object literal so I can interact with it in a better way.

What I'm trying to do here is have start() execute automatically when LiveTime object is defined.

Also need to keep track of the timeout ID so I can use that for whenever I'm calling the stop() method.

var LiveTime = {
    element: document.getElementById("current-time"),
    date: new Date(),
    timeoutId: 0,

    start: (function() {
        LiveTime.timeoutId = setTimeout(function() {
            LiveTime.date.setTime(LiveTime.date.valueOf() + 1000);

            LiveTime.element.innerHTML = ("0" + LiveTime.date.getHours()).slice(-2) + ":"
                              + ("0" + LiveTime.date.getMinutes()).slice(-2) + ":"
                              + ("0" + LiveTime.date.getSeconds()).slice(-2);
        }, 1000);
    })(),

    stop: function() {
        clearTimeout(LiveTime.timeoutId);
    }
}

Unfortunately the code is giving me a bunch of undefined errors.

Uncaught TypeError: Cannot set property 'date' of undefined

What am I doing wrong, and how can I fix that and anything else that's wrong with my code?


Solution

  • You are defining start as a self executing function. This means that when the LiveTime object is being created, start will be set to the result of that function. But since that function is running while LiveTime is still being created, LiveTime is undefined. Change the start definition to

    start: function() {
        LiveTime.timeoutId = setTimeout(function() {
            LiveTime.date.setTime(LiveTime.date.valueOf() + 1000);
    
            LiveTime.element.innerHTML = ("0" + LiveTime.date.getHours()).slice(-2) + ":"
                              + ("0" + LiveTime.date.getMinutes()).slice(-2) + ":"
                              + ("0" + LiveTime.date.getSeconds()).slice(-2);
        }, 1000);
    },
    

    and it should work (This is still your code, did not check for any other errors that may be there)