Reputation: 1052
I have a function geocode that works... I'm trying to implement a delay to prevent over query limit errors, and here is my javascript:
tmpResult = null;
setTimeout(function() {
tmpResult = geocode(facilities[j],cities[j],states[j]);
}, 100);
The variable tmpResult
has the results of my geocode.. however, tmpResult
is null
when I run the script.. is there something I'm missing?
Thanks!
Upvotes: 0
Views: 129
Reputation: 707456
tmpResult
is perfectly valid when the setTimeout()
runs and afterwards. The issue for you is probably that you are trying to use tmpResult
BEFORE the setTimeout()
has run. Remember, it will run 100ms into the future. Your other javascript will continue to run before that.
What you need to do is use the value of tmpResult
from within the setTimeout()
or call some function and pass it the value of tmpResult
.
setTimeout(function() {
var tmpResult = geocode(facilities[j],cities[j],states[j]);
callMyFunction(tmpResult);
}, 100);
setTimeout()
is asynchronous and you cannot program synchronously when using it. You must code asynchronously which means the value of tmpResult
is not valid until the timer callback executes so you can't try to use it before the timer callback fires.
As you have discovered, if you try to do this:
var tmpResult = null;
setTimeout(function() {
tmpResult = geocode(facilities[j],cities[j],states[j]);
}, 100);
console.log(tmpResult);
It will not work because your console.log(tmpResult)
statement will run BEFORE the timer fires, thus tmpResult
does not yet have a value.
FYI, you should make sure that geocode()
is not also an asynchronous function because if it is, then you will have to code asynchronously with it also.
Upvotes: 3