Home > Web Front-end > JS Tutorial > How Can I Preserve the `this` Context in JavaScript's `setInterval` Callback?

How Can I Preserve the `this` Context in JavaScript's `setInterval` Callback?

Patricia Arquette
Release: 2024-11-29 10:34:14
Original
280 people have browsed it

How Can I Preserve the `this` Context in JavaScript's `setInterval` Callback?

Preserving this in JavaScript's setInterval Callback

In JavaScript, the this keyword refers to the object that owns the currently executing code. This can become problematic when using setInterval, as the callback function is executed in a different context, losing access to the original this. To overcome this:

Accessing this in setInterval Handlers

To allow access to this in the setInterval callback, we can use the bind() method:

this.intervalID = setInterval(this.retrieve_rate.bind(this), this.INTERVAL);
Copy after login

Here, bind(this) ensures that the this within the retrieve_rate callback always refers to the object where the interval was set (i.e., the object where prefs is defined).

With this modification, you can now access this.prefs within the ajax.onload callback:

ajax.onload = function()
{
    // Access this.prefs here
}
Copy after login

The above is the detailed content of How Can I Preserve the `this` Context in JavaScript's `setInterval` Callback?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template