Javascript settimeout + callback
I have a javascript question relating to callback and timeout.
This is an example code snippet I wrote:
var f1 = function(){
var result;
window.setTimeout(
function(){
console.log("timeout in 100ms");
result = 10;
}.bind(this), 100);
return result;
};
So, I want the function to modify the variable result. I used .bind(this) to ensure that it knows what result it.
still, the out put when I run f1() is 9, not 10, which is what I have desired.
Any clues?
This Question Has 2 Answeres | Orginal Question | MiaoMiao
's answer is accepted
's answer is
You are calling the timeout to modify the value after the function already returned, so it returns the default value for result, then call the timeout, and since the value is limited in scope to the function, you have no means to return it after modification.
What you can do is this
var result = 9;
var f1 = function(){
window.setTimeout(
function(){
console.log("timeout in 100ms");
result = 10;}.bind(this), 100);
return result;};
And then after calling f1 t will return 9 then call result
and it will show 10
Result is a number. Therefore it is returned as the value
9
not a reference to an object.bind
does not have any useful effect in your scenario.bind
changes the function context (this
).Returning an object containing the value 10 will work.
There are likely better solutions to your problem.
Callbacks:
Such a function would be used like so:
Another alternative, could use Promises:
You would call such a function like so: