Home > Web Front-end > JS Tutorial > body text

How to Use \'this\' Keyword Correctly in Javascript\'s setTimeout Callback?

Barbara Streisand
Release: 2024-10-24 10:37:30
Original
392 people have browsed it

How to Use

setTimeout and "this" in JavaScript

When using the setTimeout function in JavaScript, it's crucial to understand how the this keyword works within the callback function. In some cases, you may encounter an error stating that the referenced method is undefined after a timeout delay.

Consider the following code:

<code class="javascript">test.prototype.method = function() {
    // method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";
    timeDelay = window.setTimeout(this.method, 5000);
};

test.prototype.method2 = function(name) {
    for (var i = 0; i < document.images.length; i++) {
        if (document.images[i].id.indexOf(name) > 1) {
            return document.images[i];
        }
    }
};</code>
Copy after login

In this example, the method function is called with a timeout of 5000 milliseconds. However, after the timeout, the method2 function is no longer accessible within the callback function. This is because the this keyword refers to the global object instead of the instance of the test prototype.

To resolve this issue, you can bind the this keyword to the callback function before calling setTimeout. This can be achieved by using the .bind(this) method:

<code class="javascript">test.prototype.method = function() {
    // method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";
    timeDelay = window.setTimeout(this.method.bind(this), 5000);
};</code>
Copy after login

By binding the this keyword to the callback function, you ensure that the method2 function remains accessible even after the timeout has elapsed.

The above is the detailed content of How to Use \'this\' Keyword Correctly in Javascript\'s setTimeout Callback?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!