javascripthtmlcanvascreatejs

Countdown clock timer in Javascript for Flash Canvas HTML5


Working on a simple countdown in javascript (createJS) for Flash Canvas HTML5, and I'm getting the following error:

file_Canvas.js:318 Uncaught TypeError: Cannot read property 'dtxt_days' of undefined

The error is specific to the line this.mc_counter.dtxt_days.text = days; and the 3 below that.

What am I doing wrong?

Here's the js:

this.mc_counter.dtxt_days.text = "";
this.mc_counter.dtxt_hours.text = "";
this.mc_counter.dtxt_mins.text = "";
this.mc_counter.dtxt_secs.text = "";

var end = new Date('10/19/2015 10:1 AM');

var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;

function showRemaining() {
    var now = new Date();
    var distance = end - now;
    
    this.days = Math.floor(distance / _day);
    this.hours = Math.floor((distance % _day) / _hour);
    this.minutes = Math.floor((distance % _hour) / _minute);
    this.seconds = Math.floor((distance % _minute) / _second);

    this.mc_counter.dtxt_days.text = days;
    this.mc_counter.dtxt_hours.text = hours;
    this.mc_counter.dtxt_mins.text = minutes;
    this.mc_counter.dtxt_secs.text = seconds;
}

    
timer = setInterval(showRemaining, 1000);

console.log(timer);

Solution

  • You're assigning the variables in the lines of code with errors to something that doesn't exist.

    this.days != days
    

    Instead, make sure you're getting the properties you just assigned to this.

    this.mc_counter.dtxt_days.text = this.days;
    this.mc_counter.dtxt_hours.text = this.hours;
    this.mc_counter.dtxt_mins.text = this.minutes;
    this.mc_counter.dtxt_secs.text = this.seconds;
    

    Additionally - this doesn't refer to what you think it does. Since showRemaining is a function, this in the code inside it actually refers to showRemaining. There's a couple ways to solve this. Here's arguably the simplest one:

    var self = this;
    function showRemaining() {
       self.days = ...
       self.mc_counter.dtxt_days.txt = ...
    }
    

    That simply stores a reference to the outer this. Alternatively, you can do the following:

    timer = setInterval(showRemaining.call(this), 1000);
    

    Which assigns the this inside showRemaining to the outer this.