Today it is common practice to transform node-style-callback functions into promise-style functions. So why haven't we done this for setTimeout?
...
For further actions, you may consider blocking this person and/or reporting abuse
Ok, that's so cool but... what about
clearTimeout?Because I'm sure many have thought about transforming
setTimeoutinto a promise (e.g. was common in AngularJS), but there's always a catch.There has been a debate about cancelable promises a couple of years ago, we got nothing it out of it 😕
This is a fantastic question. Without cancellable promises, you would not be able to cancel the
setTimeout.For a majority of use cases cancelling a promise is not needed. Though that doesn't mean it is not a valid use case. Throttling and debouncing is an example of a valid use case when you would want to cancel a promise.
The
sleepimplementation I created currently does not support cancellation. I have created an issue for this here: github.com/joelnet/MojiScript/issu.... This is a feature that would be great to have.Here's a very naive implementation that could support cancellation:
Bluebird also supports promise cancellation: bluebirdjs.com/docs/api/cancellati...
Converting this
Promiseto use bluebird'sPromisewould also work.Yes, that could work! 🙌
You can also consider the approach that's been taken for cancelling a
fetchpromise: it's based on a "signal" that's being created by anAbortControllerobject:You can extend your
sleepfunction to accept asignaloption and listen to anabortevent. Although it does seem a little overkill for something like this...This is interesting. I'll have to create some test project with the
.canceland anAbortController. Maybe I'll create adebounceto compare the differences.Definitely something to think about.