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.
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.
- You just found one of the reasons why you should not use strings as callbacks for setInterval/setTimeout. Have a look at the related questions to the right, I bet half of them share the same problem. – Yoshi Commented Nov 10, 2012 at 21:32
1 Answer
Reset to default 8For a great number of reasons, one of which you just ran into, never ever pass a string to setTimeout
or setInterval
. 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.
var count = 0;
alert(count);
var timer = setInterval(function(){
count = count + 1;
alert(count);
}, 10000);
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 count
is indeed a global variable.
Other problems with this stem from the fact this is basically eval
which es with its own headaches and is best to avoid entirely. Eval is Evil after all.