0

I'm trying to run a setInterval function while playing audio. So I put the setInterval inside the timeUpdate function, unfortunately it triggers on every timeUpadte.

How would I need to write it?

var audio = document.getElementById('audioElement');

audio.ontimeupdate = function () {
       setInterval(function(){ 
         console.log("test"); 
       }, 1000);
};
 <audio id="audioElement" controls>
  <source src="http://stash.rachelnabors.com/music/byakkoya_single.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio> 
vinni
  • 633
  • 2
  • 8
  • 32
  • 3
    And why do you want to do that? Sounds like an X/Y problem? – adeneo Nov 01 '16 at 14:54
  • Not sure if this is a good approach, but you could add a global boolean and switch inside onTimerUpdate – Scadge Nov 01 '16 at 14:54
  • @SergeyChupov is there I way i can trigger a function every x seconds only while a song is playing? Or can I start the interval on play and stop it on pause? Maybe I should do it this way: https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript – vinni Nov 01 '16 at 15:00
  • Your code is a browser killer. `timeupdate` event is firing every x msecs (x depends on system load). And every x msecs you create separate `setInterval`. So after 1000 secs you'll have over 1000 separately running `setInterval`s. But the point is that you don't need `setInterval` at all. `timeupdate` handler can do all the job. – hindmost Nov 01 '16 at 15:16
  • @hindmost so how would i trigger a function inside timeupdate every n seconds? – vinni Nov 01 '16 at 15:36
  • [Date.now](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) or [currentTime](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/currentTime) depending on which time you want to account. – hindmost Nov 01 '16 at 15:43

0 Answers0