Javascript settimeout + callback

    |
  • Added:
  • |
  • In: Wordpress

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

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.

var f1 = function(){ var result = { value: 9 }; window.setTimeout( function(){ console.log("timeout in 100ms"); result.value = 10;}.bind(this), 100); return result; }; 

There are likely better solutions to your problem.

Callbacks:

var f1 = function(valueCallback){ var result; window.setTimeout(function(){ console.log("timeout in 100ms"); result = 10; valueCallback(result); }; 

Such a function would be used like so:

f1(function(value)) { console.log(value); // Will print 10 after 100ms. }) 

Another alternative, could use Promises:

var f1 = function() { return new Promise(function(resolve, reject) { window.setTimeout(resolve.bind(null, 10), 100); } } 

You would call such a function like so:

f1().then(function(value) { console.log(value); // Will print 10 after 100ms. }); 

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


Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

NEED HOSTING?
Are you searching for Good Quality hosting?
You can Try It!
Connect Social With PHPAns
Top