1.0.0 • Published 4 years ago

wait-taima v1.0.0

Weekly downloads
1
License
MIT
Repository
-
Last release
4 years ago

Taima 🕒

Create timeouts, cancel them and do things after they are done in a legible way.

Why Taima?

Apps running in a browser usually need to handle timeouts (creating and cancelling) for different use cases. This library intends to make this need a bit easier providing a familiar API where a Promise will be resolved whenever the timeout (taima) expires. Adding to that, the returned Promise will allow the developer to cancel it if needed.

How Taima does it

Regular timeout

const myFuncToRunInTheFuture = () => 'foo';

const willRun = taima(myFuncToRunInTheFuture, 5000);

Cancelling a timeout

const myFuncToRunInTheFuture = () => 'foo';

const willRun = taima(myFuncToRunInTheFuture, 5000);
.
.
.
// Later...
willRun.cancel();

Waiting for the timeout to finish

const willRun = taima(myFuncToRunInTheFuture, 5000)
  .then(taimaObj => console.log(`Taima has finished`, taimaObj));

As shown above, Taima provides a straightforward way to ask for a timeout and execute a callback, chaining it with whatever is needed next. On the other hand it provides an straightforward way to cancel the timeout.

Considerations

  • This library encapsulates the use of requestAnimationFrame/cancelAnimationFrame if available and uses setTimeout/clearTimeout as a fallback.
  • As the requestAnimationFrame gets called every ~16.6 milliseconds, cancelling a taima less than 16 milliseconds after it was requested, might fail (potential improvement to be done here).

Misc

The name comes from an adaptation of the word timeout in my country Venezuela 🇻🇪.


What Taima is trying to fix

const myFuncToRunInTheFuture = () => 'foo';

window.setTimeout(myFuncToRunInTheFuture, 5000);

This will use the window setTimeout method to execute myFuncToRunInTheFuture after 5 seconds go by.

If this timeout were to be cancelled this code should be updated to something like:

const myFuncToRunInTheFuture = () => 'foo';

const timeoutId = window.setTimeout(myFuncToRunInTheFuture, 5000);
.
.
.
// Later...
window.clearTimeout(timeoutId);

Sometimes this is a bit confusing and makes it hard to follow even though the documentation on setTimeout and clearTimeout is very accurate.

There's another way to handle timeouts using requestAnimationFrame. This requires a bit of code (some of it present in this library, so it's not going to be explained here). And this approach brings with it a different type of challenges as every time the requestAnimationFrame is called a new request id is created, meaning this changes every ~60 times per second. This request id is needed to cancel (clear) the requested animation frame.

1.0.0

4 years ago