Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable inside setTimeout says it is undefined, but when outside it is defined [duplicate]

I have a class. I need to do some http work inside of a timeout. The problem I am faceing is the http variable inside the timeout keeps saying it is undefined.

export class MyClass {      http:Http:      constructor(private http:Http) {         this.http = http;     }      sendFriendRequest(){      this.http.post( ...//http variable is defined here            setTimeout(function(){                this.http.post(...  //http is not defined here         }    } } 
like image 918
user2924127 Avatar asked Mar 24 '16 20:03

user2924127


People also ask

Does setTimeout repeat?

setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.

Is setTimeout blocking?

Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute. All other statements that are not part of setTimeout() are blocking which means no other statement will execute before the current statement finishes.

Can setTimeout cause stack overflow?

Set timeout would not cause stack overflow, because it is asynchronous. It will just put the callback to the event queue and not block the execution.

Can I clear timeout inside setTimeout?

clearTimeout() inside setTimeout() method not working in JS It does "work", but your logic is incorrect. After you called clearTimeout you are calling setTimeout again. Instead of calling clearTimeout you should just exit the function.


1 Answers

The reason for this is that the callback function inside setTimeout is in a different lexical environment. This is why in ES6+ functions can be defined using =>. This is so that the code within a function shares the same scope as the function.

To fix this, you can either use ES6+ syntax, where instead of function(a,b,args){...} you would use (a,b,args) => {...}:

setTimeout(() => {   this.http.post(...); }); 

or with ES5 syntax:

var root = this;  setTimeout(function(){     root.http.post(...); }); 

Hope this helps!

like image 161
thecardkid Avatar answered Sep 28 '22 02:09

thecardkid