Home >Web Front-end >JS Tutorial >How to Preserve the `this` Context in JavaScript's `setInterval()`?
Preserving 'this' Reference in JavaScript's setInterval Handler
When working with JavaScript's setInterval() function, it's common to encounter the "this" problem. This occurs when you need to access an object's properties or methods from within the interval handler function.
Consider the following code:
prefs: null, startup: function() { // init prefs ... this.retrieve_rate(); this.intervalID = setInterval(this.retrieve_rate, this.INTERVAL); }, retrieve_rate: function() { var ajax = null; ajax = new XMLHttpRequest(); ajax.open('GET', 'http://xyz.example', true); ajax.onload = function() { // access prefs here } }
In this example, we want to access the prefs property from within the ajax.onload handler function. However, this doesn't work as expected because the this reference is lost in the interval handler.
To resolve this, you can use the bind() method to create a new function that binds the this reference. Here's how:
this.intervalID = setInterval(this.retrieve_rate.bind(this), this.INTERVAL);
By using bind(), we create a new function that has its this reference bound to the original object (this). This ensures that the prefs property is properly referenced in the ajax.onload handler.
The above is the detailed content of How to Preserve the `this` Context in JavaScript's `setInterval()`?. For more information, please follow other related articles on the PHP Chinese website!