Skip to content

Instantly share code, notes, and snippets.

@joshnuss
Last active January 16, 2022 09:54
Show Gist options
  • Save joshnuss/68c5d3d110a526fc73b1dd8628b54ebb to your computer and use it in GitHub Desktop.
Save joshnuss/68c5d3d110a526fc73b1dd8628b54ebb to your computer and use it in GitHub Desktop.
A Svelte store that acts as a clock/interval timer
<script>
import timer from './timer.js'
// create clock that updates every 500ms
const clock = timer({interval: 500})
</script>
<!-- Expression will update every 500ms -->
Current time is: {$clock}
import { readable } from 'svelte/store'
export default function(options={}) {
// create a readable store with initial value set to now
return readable(new Date(), set => {
// the update function sets the latest date
const update = () => set(new Date())
// setup an interval timer to update the store's value repeatedly over time
const interval = setInterval(update, options.interval || 1000)
// return unsubscribe callback:
// it will stop the timer when the store is destroyed
return () => clearInterval(interval)
})
}
@trilusa
Copy link

trilusa commented Jul 7, 2021

Thanks! Helped me understand stores a lot.

@paolodina
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment