Referencing this inside setInterval/setTimeout within object prototype methods
Unlike in a language like Python, a Javascript method forgets it is a method after you extract it and pass it somewhere else. You can either
Wrap the method call inside an anonymous function
This way, accessing the baz
property and calling it happen at the same time, which is necessary for the this
to be set correctly inside the method call.
You will need to save the this
from the outer function in a helper variable, since the inner function will refer to a different this
object.
var that = this;
setInterval(function(){
return that.baz();
}, 1000);
Wrap the method call inside a fat arrow function
In Javascript implementations that implement the arrow functions feature, it is possible to write the above solution in a more concise manner by using the fat arrow syntax:
setInterval( () => this.baz(), 1000 );
Fat arrow anonymous functions preserve the this
from the surrounding function so there is no need to use the var that = this
trick. To see if you can use this feature, consult a compatibility table like this one.
Use a binding function
A final alternative is to use a function such as Function.prototype.bind or an equivalent from your favorite Javascript library.
setInterval( this.baz.bind(this), 1000 );
//dojo toolkit example:
setInterval( dojo.hitch(this, 'baz'), 100);
This keyword inside a setTimeout function, which is nested under a on() method. And it is not working
You could use arrow function
to do that,
setTimeout(() => {
alert("Time Over");
$(this).parent().children('.task').toggleClass("completed");
}, milliSeconds);
If you are writing your code in ES5 then use the 3rd parameter of setTimeout
,
setTimeout(function(_this){
alert("Time Over");
$(_this).parent().children('.task').toggleClass("completed");
}, milliSeconds, this);
No output from the object functions
You can't get the return value from setInterval
in this way. Try with a callback as in the following snippet
function dd(name){ this.name=name; console.log( name ); var _this = this; this.go=function(cb) { setInterval(function() { cb(_this.name); },1000) }}var tt=new dd("corolla");tt.go(function(ret) { console.log( ret );})
How to clear an interval set in this particular way
Save a reference to the intervalID on the component (this.intervalID
), and clear it in componentWillUnmount:
class Demo extends React.Component {
componentDidMount() {
this.intervalID = setInterval( () => this.baz(), 1000 );
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
render() {
//...
}
}
Issue with calling a prototype function with setInterval
You have to bind
the this
context properly to the function reference,
self.updateTimer = setInterval(self.getUpdates.bind(self), self.updateInterval);
If you do not bind the context explicitly then the this
context inside of getUpdates
would point to window. So window.updateInterval
will be undefined
.
typescript window.setInterval() not working properly
Set interval will take take the this.repeat out of the context you need to either explicitly 'bind' the method using
setInterval(this.repeat.bind(this), 5000)
or
setInterval(()=>this.repeat(), 5000)
Related Topics
How to Break a String Across More Than One Line of Code in JavaScript
Check If an Element Is Present in an Array
Loading an Angularjs Controller Dynamically
Chrome Extension - Sendresponse Not Waiting for Async Function
How to Remove All the Options of a Select Box and Then Add One Option and Select It with Jquery
How to Prevent Form from Submitting Multiple Times from Client Side
Firebase: Setting Additional User Properties
Wrong React Hooks Behaviour with Event Listener
Manipulating Innerhtml Removes the Event Handler of a Child Element
JavaScript Document.Write Replaces All Body Content When Using Ajax
How to Get the (X, Y) Pixel Coordinates of the Caret in Text Boxes
How to Destructure into Dynamically Named Variables in Es6
JavaScript "Cannot Read Property "Bar" of Undefined
Swap Rows with Columns (Transposition) of a Matrix in JavaScript
How to Capture Response of Form.Submit
Fetch: Reject Promise and Catch the Error If Status Is Not Ok
How to Check in JavaScript If One Element Is Contained Within Another