-2

I am beginner in javascript. There is strange thing in javascript and I feel stupid

//First statement
var myVar = "Hello";
function hello() {
    document.getElementById("demo").innerHTML = myVar;
}

//second statement
var myVar = setInterval(myTimer, 1000);
function myTimer() {
    document.getElementById("demo").innerHTML = new Date().toLocaleTimeString();
}

Why the second function work without invoked it ? Unlike the first ? This caused a lot of problems to me !

jean-max
  • 1,640
  • 1
  • 18
  • 33
AmrElgendy
  • 571
  • 1
  • 4
  • 9

2 Answers2

2

Why the second function work without invoked it ? Unlike the first ?

You are passing the function myTimer to setInterval. setInterval calls the function every 1000ms. So while it is not you who directly calls the function, it is still called (by setInterval). setInterval's whole purpose is to call the function that you pass to it as argument.

In contrast, you are not doing anything with hello. You are neither calling it directly, nor are you passing it to any other function that could call it.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

From what I can gather from the comments, you seem to be confused as to why the myTimer() function works. Here's a brief explanation:

On this line

var myVar = setInterval(myTimer, 1000);

you are calling the setInterval() function. That function takes 2 parameters, which you have defined. The first one is a function; the code to be executed. The second one is the delay between each execution of said function.

On the next line, you have declared the variable myTimer to be a function which is executed with the setInterval.

Have a look at the MDN documentation for details. Specifically, it says:

var intervalID = window.setInterval(func, delay)

The parameters are defined as:

func: A function to be executed every delay milliseconds.

and

delay: The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code.

Chris
  • 57,622
  • 19
  • 111
  • 137