Timeout
setTimeout
is the usual way to call a function after some elapsed time:
import { intervalToMs } from "https://unpkg.com/ixfx/dist/flow.js"// Call `doSomething` once after one minuteconst t = window.setTimeout(doSomething, 60*1000);// or:const t = window.setTimeout(doSomething, intervalToMs({ mins: 1 }))
If you want to trigger the same timeout at different points in your code, it soon gets messy detecting and cancelling the existing timeout and scheduling a new one.
ixfx’s Flow.timeout makes this a bit simpler. Once setup, calling start()
schedules the timer, or resets if already scheduled. To cancel a started timeout, use cancel()
.
import { timeout } from "https://unpkg.com/ixfx/dist/flow.js"
// Set up onceconst fadeOut = timeout(() => { // do something after 30secs}, { secs: 30 });
// Trigger if there's a button press.// Multiple calls to .start() reset waiting periodconst el = document.getElementById(`btnStart`);el.addEventListener(`click`, () => fadeOut.start());
The callback can be cancelled and restarted. Restarting cancels the currently scheduled timeout, scheduling it anew.
fadeOut.cancel(); // cancels a timeout
// Starts (or restarts) a timeoutfadeOut.start();fadeOut.start(1000); // (re)start and change the delay period at the same time
Your callback function can use the elapsed time, if needed:
const fn = (elapsedMs) => { console.log(`Timeout after ${elapsedMs}`)}timeout(fn, { secs: 30 }).start();
Data can be passed to the callback function when running .start()
:
// Setup timeoutconst fadeOut = timeout((elapsedTime, data) => { // Function gets passed the elapsed time and data console.log(data.msg);});
// Trigger timeout with data. The first parameter is to adjust the timeout.// in this case we don't want to, so _undefined_ is passed.fadeOut.start(undefined, { msg: `hello` });