metonym / svelte-time

Svelte component and action to format a timestamp using day.js
https://metonym.github.io/svelte-time
MIT License
137 stars 8 forks source link

Suggestion: Use a single global readable store for live updates #29

Open matthewrobb opened 1 year ago

matthewrobb commented 1 year ago

Somewhat like this:

import { readable } from "svelte/store"

const NOW = readable(new Date(), (set) => {
  const timer = setInterval(() => set(new Date()), 1000)
  return () => clearInterval(timer)
})

Effectively eliminating the NEED for configurable granularity (could still support special cases) while reducing the number of timers required for like a large list of things to 1.

matthewrobb commented 1 year ago

Actually this should work for any case:

import { readable, type Readable } from "svelte/store"

const LIVE_STORES: Record<number, Readable<Date>> = {}

function liveStore(interval: number = 1000) {
  return LIVE_STORES[interval] ??= readable(new Date(), (set) => {
    const timer = setInterval(() => set(new Date()), interval)
    return () => clearInterval(timer)
  })
}
metonym commented 1 year ago

Interested in creating a PR?

matthewrobb commented 1 year ago

Sure!

matthewrobb commented 1 year ago

Not sure when I can get to this exactly. It's not quite so straight forward with how this lib is structured. You generally need to subscribe to a store at the beginning of the lifetime of a component instance but since the live prop can be dynamic we need a store that can dynamically adjust which timer it's using based on that.