Creating dynamic one-time Javascript event listeners for Audio player timestamps

I want to produce a series of unique messages based on timestamps while an audio file is playing via an HTML5 element. My approach to doing this is to loop through an object array comprised of key value pairs where the key is message and the value is the timestamp (in seconds), and create an event listener bound to the audio player’s timeupdate event. When the event fires, it checks if the current timestamp of the audio player is greater than the value of the bound key, and removes itself to avoid firing again:

function addAudio() {
  audio = document.createElement('audio');
  audio.id = "test";
  audio.src = "https://www.uscis.gov/files/nativedocuments/Track%2093.mp3";
  document.querySelector('body').prepend(audio);
}

function playAudio() {
  document.getElementById('test').play();
}

function setupListeners() {
  var items = {
    'message1': 1.5,
    'message2': 3.5,
    'message3': 4.5
  }

  for (var key in items) {
    console.log(key + " to start at " + (items[key]));

    document.getElementById('test').addEventListener('timeupdate', function() {

      if (this.currentTime > items[key]) {

        console.log(key[value])

        document.getElementById('test').removeEventListener('timeupdate', arguments.callee);
      }
    });
  }
}

addAudio();
playAudio();
setupListeners();

I’m not sure if what I’m trying to accomplish is fundamentally wrong because of the Audio player or because of my understanding of dynamic event listener generation. I can confirm the event listeners are being created, but the conditional that checks to see if the currentTime of the audio player is greater than any of the listener’s value never seems to resolve to true.

If there is a better approach to take (again, the requirement is to execute code based on a predetermined set of timestamps (with minor variance allowed given the rate of the timeupdate event firing), please let me know.

Read more here: Source link