0

I built a page where a user can input a value in seconds, and then a ping will sound at that interval. I also put together a timer, that should be in sync with the ping intervals. Like if they input 5 - the clock should be running past 5, 10, 15 ect... when the ping is sounding. For a reason I can't figure out, the sound doesn't seem to quite be sync'd with the clock and it gets worse the longer it's been running. Thanks for your help!

$(document).ready(function() {

  $('#set_ping').click(function() {
    interval = parseInt($('#ping_val').val()*1000,10);
    $('#ping_alert').text('The ping will sound every ' + interval/1000 + ' seconds.');
  });

  $('#go').click(function() {  
    timer();
    setInterval(sound, interval);

   });

  function sound() {
   $('#audio').append('<embed src="assets/audio/sound88.mp3" autostart="true" hidden="true" loop="false">');    
  }

  var seconds = 0;
  function timer() {setInterval(function() {
    $('#progress').text(seconds++/100);
  }, 10);
 }
});
jeffusu
  • 135
  • 2
  • 2
  • 7
  • 1
    Why don't you just embed it, do not set autoplay, set it to preload, and call it to play with JavaScript. beats appending the element every time. – epascarello Jan 11 '13 at 18:38

2 Answers2

0

It's because timers in JavaScript are not exactly that accurate. See here and here as well. Also, due to the fact that JavaScript is single-threaded, timers only execute when nothing else is executing. If your page is busy, stuff that are actually "scheduled" to execute get "delayed" instead.

Community
  • 1
  • 1
Joseph
  • 117,725
  • 30
  • 181
  • 234
0

Use the code from bellow:

$(document).ready(function() {
var interval;
  $('#set_ping').click(function() {
    interval = parseInt($('#ping_val').val()*1000,10);
    $('#ping_alert').text('The ping will sound every ' + interval/1000 + ' seconds.');
  });

  $('#go').click(function() {  
    timer();
    setInterval(sound, interval);

   });

  function sound() {
   $('#audio').append('<embed src="assets/audio/sound88.mp3" autostart="true"     hidden="true" loop="false">');    
  }

  var seconds = 0;
  function timer() {setInterval(function() {
    $('#progress').text(seconds++/100);
    if(seconds % interval == 0){
       // play music here 
    } 
  }, 10);
 }
});

In that code when code update the time it also check if the time (Your seconds variable) if multiple of interval variable with holds the time interval betweens sounds. Note interval is global variable

bumerang
  • 1,776
  • 21
  • 30