Home > Web Front-end > JS Tutorial > How to Turn a `setTimeout` Function into a Promise?

How to Turn a `setTimeout` Function into a Promise?

Patricia Arquette
Release: 2024-11-25 01:42:18
Original
184 people have browsed it

How to Turn a `setTimeout` Function into a Promise?

How to Turn setTimeout into a Promise

The task of creating a promise for a function that returns nothing, such as setTimeout, can be initially challenging. To understand this concept, let's refer to a modified code sample:

<br>function async(callback){</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">setTimeout(function(){
    callback();
}, 5000);
Copy after login

}

async(function(){

console.log('async called back');
Copy after login

});

Our goal is to generate a promise that async can return once the setTimeout callback is ready.

Basic Delay with Promise

Using native promises, we can create a function called later as follows:

<br>function later(delay) {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">return new Promise(function(resolve) {
    setTimeout(resolve, delay);
});
Copy after login

}

This function takes a delay in milliseconds and returns a promise that resolves after the delay expires.

Basic Delay with Value

To modify later and allow it to pass a resolution value, we need to ensure the setTimeout callback receives the value as an argument. For browsers that support providing extra arguments to setTimeout, the following code can be used:

<br>function later(delay, value) {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">return new Promise(function(resolve) {
    setTimeout(resolve, delay, value);
});
Copy after login

}

This code ensures that the value is passed to the callback and subsequently resolved by the promise.

Cancellable Delay with Value

For cases where we want to provide the ability to cancel the timeout, we can create an object with a cancel method and an accessor for the promise. When the cancel method is called, it clears the timeout and rejects the promise:

<br>const later = (delay, value) => {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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 approach provides a way to cancel a pending timeout and reject the associated promise.

The above is the detailed content of How to Turn a `setTimeout` Function into a Promise?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Previous article:Five Things I Hate About React (And How to Overcome Them) Next article:How Can I Extend JavaScript\'s `Array.prototype.indexOf()` for Internet Explorer Compatibility?
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
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template