tutorial: in the onDestroy example, explicitly show the memory leak

pull/5515/head
fivemru 5 years ago
parent 159cf86df6
commit 12a9acf5d6

@ -1,10 +1,17 @@
<script> <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> </script>
<p> <div>
The page has been open for <button on:click={toggle}>{show ? 'Destroy' : 'Show'} Inner component</button>
{seconds} {seconds === 1 ? 'second' : 'seconds'} <p>counter={counter}</p>
</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'; import { onDestroy } from 'svelte';
export function onInterval(callback, milliseconds) { 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> <script>
import { onInterval } from './utils.js'; import Inner from './Inner.svelte';
let seconds = 0; let counter = 0;
onInterval(() => seconds += 1, 1000); let show = true;
const toggle = () => (show = !show);
const handleTick = () => (counter += 1);
</script> </script>
<p> <div>
The page has been open for <button on:click={toggle}>{show ? 'Destroy' : 'Show'} Inner component</button>
{seconds} {seconds === 1 ? 'second' : 'seconds'} <p>counter={counter}</p>
</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>

@ -10,8 +10,8 @@ For example, we can add a `setInterval` function when our component initialises,
<script> <script>
import { onDestroy } from 'svelte'; import { onDestroy } from 'svelte';
let seconds = 0; let counter = 0;
const interval = setInterval(() => seconds += 1, 1000); const interval = setInterval(() => counter += 1, 1000);
onDestroy(() => clearInterval(interval)); onDestroy(() => clearInterval(interval));
</script> </script>
@ -37,7 +37,7 @@ export function onInterval(callback, milliseconds) {
<script> <script>
import { onInterval } from './utils.js'; import { onInterval } from './utils.js';
let seconds = 0; let counter = 0;
onInterval(() => seconds += 1, 1000); onInterval(() => counter += 1, 1000);
</script> </script>
``` ```
Loading…
Cancel
Save