Why cant I call my function in setInterval() inside a class ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why cant I call my function in setInterval() inside a class ?

In the code , calling this.update() works normally but not inside a setTimeout() Can anyone tell me why and how to fix it . https://code.sololearn.com/WUi5cd1vF6c2/?ref=app

16th Jun 2018, 11:34 AM
Utkαrsh
Utkαrsh - avatar
10 Answers
+ 5
this is out of scope when use in timer function. Declare a this var for timer function use. eg. var that = this; setTimeout(function(){ console.log("what") that.update(); },1000);
16th Jun 2018, 12:00 PM
Calviղ
Calviղ - avatar
+ 5
do this: var self = this; //error this.update() is not a function setTimeout(function(){ console.log("what") self.update(); },1000); //************ this inside the setTimeout function is of a different context (it's not the same this) we have to save it to a variable before and use it then
16th Jun 2018, 12:01 PM
Burey
Burey - avatar
+ 5
damn Calviղ is a quick one ._.
16th Jun 2018, 12:01 PM
Burey
Burey - avatar
+ 5
i submit to you oh mighty Calviղ 🙌
16th Jun 2018, 12:05 PM
Burey
Burey - avatar
+ 5
you earned it >:D
16th Jun 2018, 12:11 PM
Burey
Burey - avatar
+ 3
The timer function run in separate execution using Window object, so the "this" points to Window global object in timer function. Btw Utkαrsh the program generates nice effect ☺👍🏼
16th Jun 2018, 3:43 PM
Calviղ
Calviղ - avatar
+ 2
It's my honour to be called mighty by Burey 😁
16th Jun 2018, 12:09 PM
Calviղ
Calviղ - avatar
+ 2
Thank You Burey and Calviղ , I get it now. Calvin get the best answer for the speed :-P I thought that might be the problem , but I only tried this.this.update() ..lol What does the "this" point to inside the setTimeout anyway the function itself or something else
16th Jun 2018, 3:29 PM
Utkαrsh
Utkαrsh - avatar
+ 2
The proper solution is: setTimeout(function(){ console.log("what") this.update(); }.bind(this) ,1000); Simply binding the context of ‘this’ to the function. The bind function returns another function, wrapping the initial one and setting ‘this’ to whatever you supply as a parameter of the bind method. “var that = this” is frowned upon in industry, but unavoidable in some situations - not this one.
17th Jun 2018, 3:42 PM
Stuart
+ 1
Burey 🤣
16th Jun 2018, 12:03 PM
Calviղ
Calviղ - avatar