Connecting Tech Pros Worldwide Forums | Help | Site Map

How can i use external variables in "setInterval" code?

Newbie
 
Join Date: Jun 2009
Posts: 16
#1: Jul 7 '09
When i run this functions it says the count is undefined.
Expand|Select|Wrap|Line Numbers
  1. function hello(){
  2.     var count = 0;
  3.     var timer = setInterval('count+=1;alert(count);',2000);
  4. }
  5.  

Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 4,300
#2: Jul 8 '09

re: How can i use external variables in "setInterval" code?


some functions change the variable scope. setInterval() and setTimeout() will have global scope and because count was defined inside a function, count will have the function's local scope and not the global one. thus count is undefined (on global scope).

to work around that you need two things, a function for the code to execute and a closure to preserve the values.

(will be back when I got more time…)
rnd me's Avatar
Expert
 
Join Date: Jun 2007
Location: Urbana IL
Posts: 417
#3: Jul 8 '09

re: How can i use external variables in "setInterval" code?


Expand|Select|Wrap|Line Numbers
  1. function hello(){
  2.     var count = 0;
  3.     var timer = setInterval( function(){  count+=1;alert(count); },2000);
  4. }
  5.  
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 4,300
#4: Jul 8 '09

re: How can i use external variables in "setInterval" code?


some articles about closures:
JavaScript Closures for Dummies
JavaScript Closures 101
JavaScript Closures

and some about Scope
Scope in JavaScript
Explaining JavaScript Scope and Closures
Reply

Tags
external variable, setinterval