Francesco Francesco - 2 months ago 16
Javascript Question

ReferenceError is not defined

This is my script:

<script>
document.addEventListener("DOMContentLoaded", function(event) {
var START_DATE_1 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
var INTERVAL_1 = 3; // in seconds
var INCREMENT_1 = 1; // increase per tick
var START_VALUE_1 = 0; // initial value when it's the start date
var count_1 = 0;

var msInterval_1 = INTERVAL_1 * 1000;
var now_1 = new Date();
count_1 = parseInt((now_1 - START_DATE_1)/msInterval_1) * INCREMENT_1 + START_VALUE_1;
document.getElementById('counter_1').innerHTML = count_1;
setInterval("count_1 += INCREMENT_1; document.getElementById('counter_1').innerHTML = count_1;", msInterval_1);
});
</script>


I've placed it inside a Joomla module. Firebug says: "ReferenceError: count_1 is not defined"

Why? How can I solve it?

Answer

You should pass a function instead of a string to the setInterval call. When you pass a string, it is executed in the global scope, and count_1 variable exists only in the scope of the callback function passed to addEventListener.

<script>
  document.addEventListener("DOMContentLoaded", function(event) {
    var START_DATE_1 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
    var INTERVAL_1 = 3; // in seconds
    var INCREMENT_1 = 1; // increase per tick
    var START_VALUE_1 = 0; // initial value when it's the start date
    var count_1 = 0;

    var msInterval_1 = INTERVAL_1 * 1000;
    var now_1 = new Date();
    count_1 = parseInt((now_1 - START_DATE_1)/msInterval_1) * INCREMENT_1 + START_VALUE_1;
    document.getElementById('counter_1').innerHTML = count_1;
    setInterval(function() {
      count_1 += INCREMENT_1;
      document.getElementById('counter_1').innerHTML = count_1;
    }, msInterval_1);
  });
</script>