mirror of https://github.com/sveltejs/svelte
parent
159cf86df6
commit
12a9acf5d6
@ -1,10 +1,17 @@
|
||||
<script>
|
||||
import { onDestroy } from 'svelte';
|
||||
import Inner from './Inner.svelte';
|
||||
|
||||
let seconds = 0;
|
||||
let counter = 0;
|
||||
let show = true;
|
||||
|
||||
const toggle = () => (show = !show);
|
||||
const handleTick = () => (counter += 1);
|
||||
</script>
|
||||
|
||||
<p>
|
||||
The page has been open for
|
||||
{seconds} {seconds === 1 ? 'second' : 'seconds'}
|
||||
</p>
|
||||
<div>
|
||||
<button on:click={toggle}>{show ? 'Destroy' : 'Show'} Inner component</button>
|
||||
<p>counter={counter}</p>
|
||||
{#if show}
|
||||
<Inner callback={handleTick} />
|
||||
{/if}
|
||||
</div>
|
||||
|
@ -0,0 +1,10 @@
|
||||
<script>
|
||||
export let callback;
|
||||
export let interval = 1000;
|
||||
|
||||
import { onInterval } from './utils.js';
|
||||
|
||||
onInterval(callback, interval);
|
||||
</script>
|
||||
|
||||
<p>This component will execute callback every {interval} milliseconds</p>
|
@ -1,5 +1,9 @@
|
||||
import { onDestroy } from 'svelte';
|
||||
|
||||
export function onInterval(callback, milliseconds) {
|
||||
// implementation goes here
|
||||
const interval = setInterval(callback, milliseconds);
|
||||
|
||||
onDestroy(() => {
|
||||
// After the component is destroyed, setInterval will continue to work, fix it here
|
||||
});
|
||||
}
|
@ -1,11 +1,17 @@
|
||||
<script>
|
||||
import { onInterval } from './utils.js';
|
||||
import Inner from './Inner.svelte';
|
||||
|
||||
let seconds = 0;
|
||||
onInterval(() => seconds += 1, 1000);
|
||||
let counter = 0;
|
||||
let show = true;
|
||||
|
||||
const toggle = () => (show = !show);
|
||||
const handleTick = () => (counter += 1);
|
||||
</script>
|
||||
|
||||
<p>
|
||||
The page has been open for
|
||||
{seconds} {seconds === 1 ? 'second' : 'seconds'}
|
||||
</p>
|
||||
<div>
|
||||
<button on:click={toggle}>{show ? 'Destroy' : 'Show'} Inner component</button>
|
||||
<p>counter={counter}</p>
|
||||
{#if show}
|
||||
<Inner callback={handleTick} />
|
||||
{/if}
|
||||
</div>
|
||||
|
@ -0,0 +1,10 @@
|
||||
<script>
|
||||
export let callback;
|
||||
export let interval = 1000;
|
||||
|
||||
import { onInterval } from './utils.js';
|
||||
|
||||
onInterval(callback, interval);
|
||||
</script>
|
||||
|
||||
<p>This component will execute callback every {interval} milliseconds</p>
|
Loading…
Reference in new issue