0

Hi I'm trying to find out how would I put a 10 second delay for the mouseover to start playing audio?

Here is the code I have been working with.

function PlaySound(soundobj) {
  var thissound = document.getElementById(soundobj);
  thissound.play();
}

function StopSound(soundobj) {
  var thissound = document.getElementById(soundobj);
  thissound.pause();
  thissound.currentTime = 0;
}
<div onmouseover="PlaySound('mySound')" onClick="StopSound('mySound')">
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
troxie
  • 21
  • 6

2 Answers2

1

You could try this if you want the events to keep track of the timeout and also whether the audio is playing or not.

function MouseAudio(element, audio) {
  this.div = element;
  this.audio = audio;
  this.timeout = null;

  this.init();
}

MouseAudio.prototype.init = function() {
  var self = this;

  this.div.addEventListener('mouseover', function(event) {
    console.log('moused over - timeout set');

    if (self.timeout) {
      clearTimeout(self.timeout);
    }

    self.timeout = setTimeout(function() {
      console.log('playing sound');
      self.audio.play();
      self.timeout = null;
    }, 10000);
  });

  this.div.addEventListener('mouseout', function() {
    if (self.timeout) {
      console.log('moused out - timeout cancelled');
      clearTimeout(self.timeout);
      self.timeout = null;
    } else if (!self.audio.paused) {
      console.log('moused out - pausing sound');
      self.audio.pause();
      self.audio.currentTime = 0;
    }
  });

  this.div.addEventListener('click', function() {
    if (self.timeout) {
      console.log('clicked - timeout cancelled');
      clearTimeout(self.timeout);
      self.timeout = null;
    } else if (!self.audio.paused) {
      console.log('clicked - pausing sound');
      self.audio.pause();
      self.audio.currentTime = 0;
    }
  });
};

var mouseAudio = new MouseAudio(document.getElementById('div'), document.getElementById('audio'));
#div {
  background: grey;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
<div id="div">Click Me</div>
<audio id="audio" src="http://anything2mp3.com/system/files/mstr1/Rick%20Astley%20-%20Never%20Gonna%20Give%20You%20Up_dQw4w9WgXcQ_youtube.mp3"></audio>
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
0

You could add a timeout that will call itself after a certain amount of milliseconds.

function PlaySound(soundobj) {
  setTimeout(function() {
    var thissound = document.getElementById(soundobj);
    thissound.play();
  }, 10 * 1000);
}
gonz
  • 5,226
  • 5
  • 39
  • 54
peterpeterson
  • 1,315
  • 2
  • 14
  • 38