Last active
January 16, 2022 09:54
-
-
Save joshnuss/68c5d3d110a526fc73b1dd8628b54ebb to your computer and use it in GitHub Desktop.
A Svelte store that acts as a clock/interval timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice one.
REPL: https://svelte.dev/repl/4c0d570310854dd4b04971597720fb9f