By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,466 Members | 1,141 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,466 IT Pros & Developers. It's quick & easy.

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

P: 22
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.  
Jul 7 '09 #1
Share this Question
Share on Google+
3 Replies


Dormilich
Expert Mod 5K+
P: 8,639
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…)
Jul 8 '09 #2

rnd me
Expert 100+
P: 427
Expand|Select|Wrap|Line Numbers
  1. function hello(){
  2.     var count = 0;
  3.     var timer = setInterval( function(){  count+=1;alert(count); },2000);
  4. }
  5.  
Jul 8 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.