Reputation: 19
I'm trying to get a variable from a setInterval() function but it always says that string is not defined. Code example below:
setInterval(function(){
var String = "test";
}, 1);
console.log(String)
what it should do is that it should log "test" into the console many times. but it does not work. any help or suggestions?
Edit: it works now. correct code is
setInterval(function(){
var myString = "test";
console.log(myString);
},1);
Upvotes: 0
Views: 1179
Reputation: 685
This should solve you issue. But kindly read the explanation below to understand.
setInterval(function(){
var something = "test";
console.log(something)
}, 1);
So, basically there were two issues with your code here,
1.) var String will overwrite the actual javascript String object, But that is not the reason you are getting the error of undefined
2.) The Reason you were getting the error is related to local scope vs global scope in Javascript. In the above question you defined a variable in the local function scope and were trying to access the same variable in the global scope.
Upvotes: 1
Reputation: 1157
I think the problem in using wrong name for variable. String is the name of a class. Try instead var myString = 'test'
. Leave the order the same. Should work
EDIT Sorry guys, late night, my eyes are closing :)
Put your console inside the callback! And still, don't use String as a variable!
Take a look here for naming your vars: http://www.javascripter.net/faq/reserved.htm
Upvotes: 0
Reputation: 4670
As has been mentioned in the comments, you are defining the variable in the wrong scope. Specifically, you are defining it within the anonymous function you are calling, so it can only be referenced within that function. Defining the variable outside the function will fix your issue.
var myString = "hello world";
setInterval(function(){
myString = "test";
}, 1);
// this will still log 'hello world', not 'test' because
// the code in your interval has not run yet
console.log(myString)
setTimeout(function(){
// this will log 'test' because the code in the interval
// has now had a chance to run
console.log(myString)
}, 5);
Upvotes: 0
Reputation: 1396
Your var String is inside your function, and the console.log is making a request from outside your function, so the variable is out of scope for your console.log.
Correct syntax would be:
setInterval(function(){
var String = "test";
console.log(String);
},1);
The above code does work, but renaming String to something like myString would be better practice.
Upvotes: 1