title: How to set the duration of the audio in React/Typescript?
body: <p>I'm working on a web app using React and TypeScript.
  I made a component called SoundEffect, which takes the sound type as a prop, and plays the mp3 according to its type.</p>
  <pre><code>interface ISoundEffectProps {
      soundType: string,
      // duration?: number, &lt;- want to add this
  }
  
  const SoundEffect: React.FunctionComponent&lt;ISoundEffectProps&gt; = (props) =&gt; {
    const sound = soundSelector(props.soundType)
    return (
      &lt;div&gt;
          &lt;audio src={sound} autoPlay&gt;&lt;/audio&gt;
      &lt;/div&gt;
    );
  };
  
  export default SoundEffect;
  </code></pre>
  <p>soundSelector() takes the soundType as a string and returns an mp3 file. Now, I want to add duration to this, so when this component is rendered, like this:</p>
  <pre><code>&lt;SoundEffect soundType=&quot;count-down&quot; duration=3000/&gt;
  </code></pre>
  <p>it only plays for 3 seconds and stops. Right now, I have to prepare separate mp3 files for different durations, which seems redundant. I can't add any buttons to this component, so I don't think I can have a component that can fire a function (correct me if I'm wrong). If anyone knows any solution or libraries/packages that would help me solve this issue, then please help me. Thanks</p>
  <p>------I'll write a solution in below------</p>
  <pre><code>interface ISoundEffectProps {
    id: string,
    soundType: string,
    duration?: number,
  }
  
  const SoundEffect: React.FunctionComponent&lt;ISoundEffectProps&gt; = (props) =&gt; {
    const sound = soundSelector(props.soundType); // &quot;../assets/sounds/example.mp3&quot;
    const audio = document.getElementById(props.id) as HTMLAudioElement; 
  // without &quot;as HTMLAudioElement&quot;, audio becomes HTMLElement, which does not have pause() method. 
  
    function startTimer(duration: number) {
      if (audio != null) { // &lt;- audio.pause() creates uncaught typeerror when audio is null
        const interval = setInterval(() =&gt; {
          audio.pause();
        }, duration 1000);
      }
    }
    return (
      &lt;div&gt;
          &lt;audio autoPlay id={props.id} onPlay={()=&gt; startTimer(props.duration || 10)}&gt;
            &lt;source src={sound} type=&quot;audio/mp3&quot;/&gt;
          &lt;/audio&gt;
      &lt;/div&gt;
    );
  }
  </code></pre>
  <p>Now, I can call for this component like:</p>
  <pre><code>&lt;SoundEffect id=&quot;beep_id&quot;, soundType=&quot;beep&quot;, duration={5}/&gt;
  </code></pre>
  <p>This component stops its sound after 5 seconds. If I put duration={10}, it stops after 10 seconds.</p>