I do not understand what is wrong. I have three codes:
First:
<script language="JavaScript" type="text/javascript">
var count = 0;
alert(count);
var timer = setInterval("count = count + 1; alert(count);",10000);
</script>
Second:
<script language="JavaScript" type="text/javascript">
function countdown()
{
var count = 0;
alert(count);
var timer = setInterval("count = count + 1; alert(count);",10000);
}
countdown();
</script>
Third:
<script language="JavaScript" type="text/javascript">
var count = 0;
function countdown()
{
alert(count);
var timer = setInterval("count = count + 1; alert(count);",10000);
}
countdown();
</script>
The first code works fine, the second produces an error in the “setInterval” line: “count is not defined”, and the third code works fine again. The scope of the “count” variable should be global for the setInterval function in the second code. Why is it not? I am using Mozilla Firefox.
Thanks.
For a great number of reasons, one of which you just ran into, never ever pass a string to
setTimeoutorsetInterval. Ever. I mean it. There is never a good reason.Pass a function instead. The ability to pass function objects around is one JS best features.
The problem you are facing is that code as a string in this manner won’t respect scope. It will execute in the global scope, which is a place your variable doesn’t exist in your 2nd and 3rd snippets. And the first snippet works because
countis indeed a global variable.Other problems with this stem from the fact this is basically
evalwhich comes with its own headaches and is best to avoid entirely. Eval is Evil after all.