'How to write a "Delayed" svelte component?

I'm trying to write a Svelte component that hides its slot during the time specified.

For example, this next line should hide the paragraph during 3 seconds

<Delayed mili_time={3000}> <p>some text</p> <Delayed>

My attempt is not working and nothing is being shown (plus the log is shown though no errors are being raised) I'd love to receive some help, tips or guidance.

The attempt:

<script>

import { onMount} from "svelte";

  export let mili_time = 500;
  let shown = false;


  onMount(
    setTimeout(() => {
      console.log("delayed!");
      shown = true;
    }, mili_time)
  );
</script>

{#if shown}
<slot />
{/if}


<style></style>

Thanks in advance to anyone reading or answering for getting till the end of the question ^^



Solution 1:[1]

your onMount is badly formatted, it takes as an argument a function while you have a function call.

The correct format would be:

onMount(() => setTimeout(....)

This way the function () => setTimeout(...) will be executed.

In your code, the setTimeout function is called and the return value of that function (a reference to the timeout) is passed into onMount

Solution 2:[2]

With a 100% native Component:

<delayed-content delay="1000" hidden>
  <h1>Hello World</h1>
</delayed-content>
<script>
  customElements.define("delayed-content", class extends HTMLElement {
    connectedCallback() {
      setTimeout(() => {
        this.removeAttribute("hidden");
      }, Number(this.getAttribute("delay")));
    }
  });
</script>

Solution 3:[3]

You can set a timeout after rendering and use a CSS class to hide the element as follows:

<script>
  import { onMount } from 'svelte';

  export let timeout = 3000;
  export let hidden = false;

  onMount(() => {
    setTimeout(() => {
      hidden = true;
    }, timeout);
  });
</script>

<div class:hidden>
  <p>Some cool content here</p>
</div>

<style type="text/css">
  .hidden {
    display: none;
  }
</style>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stephane Vanraes
Solution 2 Danny '365CSI' Engelman
Solution 3 Esteban Borai