UNPKG

@grail-ui/svelte

Version:

[![NPM](https://img.shields.io/npm/v/@grail-ui/svelte)](https://www.npmjs.com/package/@grail-ui/svelte) [![minified](https://img.shields.io/bundlephobia/min/@grail-ui/svelte)](https://bundlephobia.com/package/@grail-ui/svelte) [![minified + zipped](https:

49 lines (48 loc) 1.21 kB
import { get, writable } from 'svelte/store'; import { isClient } from '../util/is.js'; import { toReadable } from '../util/store.js'; import { tryOnDestroy } from '../util/lifecycle.js'; export const createTimeout = (cb, ms, { immediate = true, autoStop = true } = {}) => { const isPending = writable(false); const delay = writable(ms); let timer = undefined; function clear() { if (timer) { clearTimeout(timer); timer = undefined; } } function stop() { isPending.set(false); clear(); } function start(...args) { clear(); const $delay = get(delay); if ($delay > 0) { isPending.set(true); timer = setTimeout(() => { isPending.set(false); timer = undefined; cb(...args); }, $delay); } else { cb(...args); } } if (immediate) { isPending.set(true); if (isClient) start(); } if (autoStop) { tryOnDestroy(stop); } return { isPending: toReadable(isPending), start, stop, delay, }; };