Home > Web Front-end > JS Tutorial > How to Preserve the `this` Context in JavaScript's `setInterval()`?

How to Preserve the `this` Context in JavaScript's `setInterval()`?

DDD
Release: 2024-12-05 18:25:11
Original
225 people have browsed it

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
  }
}
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template