Home >Web Front-end >JS Tutorial >How Can I Access `this` Correctly Inside a JavaScript `setInterval` Handler?
Accessing this from a JavaScript setInterval Handler
When using setInterval in JavaScript, it can be challenging to access the object instance (this) within the handler function. This is because setInterval creates a new context for the handler function.
To resolve this issue, we can bind the handler to the object instance, ensuring that it has access to the this keyword. Here's how:
this.intervalID = setInterval(this.retrieve_rate.bind(this), this.INTERVAL);
In this modified code, the bind method is used to create a new function that is bound to the current object instance. This function is then passed as the handler to setInterval.
Within the retrieve_rate handler function, you now have access to the this keyword and can use it to access the prefs property:
retrieve_rate: function() { // access prefs here // this.prefs }
The above is the detailed content of How Can I Access `this` Correctly Inside a JavaScript `setInterval` Handler?. For more information, please follow other related articles on the PHP Chinese website!