Javascript function arguments has to be a string?

javascript

Solution

`setInterval()` takes as its first argument

- A string of code to be evaluated (`'updateClock()'`) - This is not the preferred use, as it relies on `eval()`. The string is evaluated as JavaScript code.

- A pointer to a function (`updateClock`) - Note the lack of parens. In JavaScript, a defined function can be referenced, not called, by using its name without `()`. The pointer can also be an anonymous function as in `setInterval(function(){stuff...}, time)`, which is effectively the same thing as a reference to a defined function -- both point to a function's location in memory, whether or not it has a name.

So in your case, the preferred usage would be:

<script type="text/javascript">
  setInterval(updateClock, 1000);
</script>

Same goes for its cousin `setTimeout()`.

Problem

I'm new to javascript so I'm not sure why it's behaving like this. I have a clock function: ``` function updateClock() { var currentTime = new Date(); var currentHours = currentTime.getHours(); var currentMinutes = currentTime.getMinutes(); var currentSeconds = currentTime.getSeconds(); var currentMilliseconds = currentTime.getMilliseconds(); // Pad the minutes and seconds with leading zeros, if required currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes; currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds; // Choose either "AM" or "PM" as appropriate var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM"; // Convert the hours component to 12-hour format if needed currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours; // Convert an hours component of "0" to "12" currentHours = ( currentHours == 0 ) ? 12 : currentHours; // Update the time display document.getElementById("clock").innerHTML = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay; } ``` which is in a separate `clock.js` file. I include that file in the head. I place this under the `clock div`: ``` <script type="text/javascript"> setInterval("updateClock()", 1000); </script> ``` And it works. But if I change it to `setInterval(updateClock(), 1000);`, it won't work. I spent a while trying to figure out why the function only executed once until I found out I needed to put quotes around the function call. Coming from different languages background, I don't know why you need to put quotes around it? It looks like I'm passing a string `"updateClock()"` to the function instead of another function. I see other people's code where they just define the whole function as a parameter such as `setInterval(function(){ ... }, 1000)`.

Original source