简体   繁体   中英

setInterval inside a function produces an error: variable is not defined

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 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 comes with its own headaches and is best to avoid entirely. Eval is Evil after all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM