Your first attempt is a synax error:
var timer = setTimeout('countDown('secs')',1000);
You're trying to pass a string to setTimeout
(which is a bad idea to begin with), but you're not creating the string properly.
The single quotes around the word secs
are not escaped, so you're actually passing the string literal countDown(
followed by the variable secs
, followed by the string literal )
.
Because there are no operators between the strings, this is invalid syntax.
However, when you use the +
symbols, you're adding 3 strings together to create the method invocation you want (the +
operator is used to concatenate strings in JavaScript):
'countDown(' + 'secs' + ')' === 'countDown(secs)'
The three strings added together create a string that contains valid JavaScript, so it can be passed to the setTimeout() function.
Although you can pass a string to setTimeout(), the better approach is to pass a function reference.
This is typically done with an anonymous function like this:
setTimeout(function () {
countDown(secs);
}, 1000);
If you don't need to pass a parameter, you can do this:
function countDown() {
alert("10... 9... 8...");
}
setTimeout(countDown, 1000);
Note that when a function reference is specified as a variable, you do not use the ()
symbols. When you use parentheses after a function in JavaScript, the function is invoked.