Home > Web Front-end > JS Tutorial > How Can I Turn `setTimeout` into a Promise in JavaScript?

How Can I Turn `setTimeout` into a Promise in JavaScript?

Barbara Streisand
Release: 2024-12-05 07:08:09
Original
517 people have browsed it

How Can I Turn `setTimeout` into a Promise in JavaScript?

Turning setTimeout into a Promise

Overview

In this article, we'll explore how to transform setTimeout, a function that executes a callback after a specified delay, into a Promise that can be used to handle asynchronous operations.

Native Promises

Modern JavaScript supports native Promises that provide a convenient way to represent asynchronous operations. To convert setTimeout into a Promise, we can wrap it in a Promise constructor and pass the resolve function as the callback:

function later(delay) {
    return new Promise((resolve) => {
        setTimeout(resolve, delay);
    });
}
Copy after login

This function will return a Promise that resolves after the specified delay.

Customized Promises

If you prefer to create your own Promise implementation, you can define a promise prototype and use it as follows:

function setTimeoutReturnPromise() {
    function promise() { }
    
    promise.prototype.then = function() {
        console.log('timed out');
    };

    setTimeout(() => {
        return this;  // Return the promise object
    }, 2000);

    return new promise();
}
Copy after login

Cancellable Promise

To create a cancellable Promise, we can wrap setTimeout in a custom object that provides a cancel method:

const later = (delay, value) => {
    let timer = 0;
    let reject = null;
    const promise = new Promise((resolve, _reject) => {
        reject = _reject;
        timer = setTimeout(resolve, delay, value);
    });
    
    return {
        get promise() { return promise; },
        cancel() {
            if (timer) {
                clearTimeout(timer);
                timer = 0;
                reject();
                reject = null;
            }
        }
    };
};
Copy after login

This object returns a Promise and a cancel method that can be used to terminate the operation.

The above is the detailed content of How Can I Turn `setTimeout` into a Promise in JavaScript?. 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