skim skim - 5 months ago 10
HTML Question

Function call using single quotes vs no quotes

The following pieces of code uses the function setInterval() to continually update a 'clock'. The only difference is in the function call setInterval().

When I change the setInterval argument from

setInterval('updateTime()',1000);


to

setInterval(updateTime(),1000);


[from single to no quotes], it does not work. Can anyone explain this to me?

Single Quotes:

<head>
<script>
function updateTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var now= h+':'+m+':'+s;
document.getElementById('timer').innerHTML = h+':'+m+':'+s;//set the text in 'timer' id below to the date
setInterval('updateTime()', 1000); //////SEE THIS LINE//////
}
</script>
</head>
<body>
<p id='timer'> Time </p>
<script>
updateTime();
</script>
</body>


No Quotes:

<head>
<script>
function updateTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var now= h+':'+m+':'+s;
document.getElementById('timer').innerHTML = h+':'+m+':'+s;//set the text in 'timer' id below to the date
setInterval(updateTime(), 1000);//////SEE THIS LINE//////
}
</script>
</head>
<body>
<p id='timer'> Time </p>
<script>
updateTime();
</script>
</body>


Online js console for testing can be found here: https://jsfiddle.net/

Answer

Try doing this setInterval(updateTime, 1000); without ()

Now coming to the question why.

The Setinterval function evaluates the content if string and executes if function name

Hope that helps

Comments