Home > Web Front-end > JS Tutorial > How Can I Correctly Pass Context to a `setTimeout` Callback?

How Can I Correctly Pass Context to a `setTimeout` Callback?

Patricia Arquette
Release: 2024-12-25 22:25:23
Original
292 people have browsed it

How Can I Correctly Pass Context to a `setTimeout` Callback?

Pass Context to setTimeout Callback

Passing the correct context to the setTimeout callback can be challenging, especially when working with object methods. Initially, when referencing this within the callback, it often leads to the global object being used.

To resolve this, there are several approaches:

1. Store the Reference (ES5 and Earlier):

var that = this;
if (this.options.destroyOnHide) {
     setTimeout(function() { that.tip.destroy() }, 1000);
}
Copy after login

This technique uses a temporary variable (that) to save the context from which setTimeout is called.

2. bind Method (ES5 and Later):

if (this.options.destroyOnHide) {
     setTimeout(function() { this.tip.destroy() }.bind(this), 1000);
}
Copy after login

The bind method creates a new function with a predefined this value. In this case, this is set to the object before calling setTimeout.

3. Arrow Functions (ES6 and Later):

if (this.options.destroyOnHide) {
     setTimeout(() => { this.tip.destroy() }, 1000);
}
Copy after login

Arrow functions inherit their lexical this context, which is the same as the object calling setTimeout. This eliminates the need for binding or storing this.

4. Passing Arguments to setTimeout (HTML5):

if (this.options.destroyOnHide) {
     setTimeout(function(that) { that.tip.destroy() }, 1000, this);
}
Copy after login

HTML5 introduced a feature in setTimeout that allows passing additional arguments to the callback. Here, this is passed as an argument and accessed within the callback function.

The above is the detailed content of How Can I Correctly Pass Context to a `setTimeout` 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