0

Below is my code. When I'm calling myDate variable outside of myTime() function to create a Date() object, the setInterval() function don't fire but when it's inside myTime() function. As I know myDate variable is a global variable and it should work same inside or outside of the function. But why here the setInterval() method not firing while I'm creating the Date() object outside of the function? Experts explain the things. TIA

var myDate = new Date();
    function myTime(){
        document.getElementById('text').innerHTML = myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds();
    }
    setInterval(myTime, 1000);

1 Answers1

1

You are right: myDate variable is accessible from myTime() function, but if it is declared outside of it, its value doesn't change. In the following snippet i've created one more external variable i to show that it is accessible from within the function:

var myDate = new Date();
var i = 0;
function myTime() {
    document.getElementById('text').innerHTML = myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() + " (" + i++ + ")";
}
setInterval(myTime, 1000);
<div id="text"></div>

On the other hand, if you declare myDate variable inside the function, it will be created each time function is called - every second:

function myTime() {
    var myDate = new Date();
    document.getElementById('text').innerHTML = myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds();
}
setInterval(myTime, 1000);
<div id="text"></div>
Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42