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).
2 Answers 2
setInterval() takes as its first argument
- A string of code to be evaluated (
'updateClock()') - This is not the preferred use, as it relies oneval(). 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 insetInterval(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().
6 Comments
()? But otherwise I still use () to make function calls?setTimeout(updateClock(), 1000), updateClock is called once, and the return value is passed to setInterval.updateClock() executes it right now. If you want to pass a reference to the function to some other function so it can call it later, you do not use the parens setTimeout(updateClock, 1000).Have you tried
setInterval( updateClock, 1000);
2 Comments
() at the end.