Dynamite Media
Dynamite Media

Reputation: 169

JS setTimeout not firing on onclick

I have been using this for a odometer on my site http://github.hubspot.com/odometer/ , it is great but i can not seem to get it t o be able to work on a button onclick action. it will only work when page is loaded. i have tried to add to other functions like a simple window.alert the alert will work but it wont initiate the setTimeOUt

here is my latest code:

<script>

function playSound() {

    setTimeout(function(){

    var audio = new Audio('sounds/machine-002-short.mp3');
    var audio2 = new Audio('sounds/coin-drop-4.mp3');

    audio.play();
    audio.volume = 0.65;
    audio.currentTime = 0.90;

    audio2.pause();
    audio.addEventListener("ended", function() {
    audio2.play();
    audio2.volume = 1.5;

        }); // event listener

    $('.odometer').html(<?php echo $Display;?>);
  }, 1000);  
} 
</script>

and the button:

<button id="submit" type="submit" type="button" name="roll" onclick="playSound();">Start</button>

if i just add a winow.alert it works just not with this set time out, im very inexperienced in JS so i am sure it is something simple

Upvotes: 0

Views: 215

Answers (1)

mplungjan
mplungjan

Reputation: 177684

  • a button can submit (type=submit - default) or not (type=button)
  • If you need to submit the form, you cannot submit until after the setTimeout has run
  • if the textarea is .odometer, use .val() instead of .html()
  • Perhaps you do NOT want to submit the form, but instead AJAX in the content of the action. Like this:
function getContent() {
  $.get($("#form1").prop("action", {data:$("#odometer").val()},function(data) {
     $('#odometer').val(data); // here we replace the $Display with what is returned
  });
}
function playSound() {

  setTimeout(function() {

    var audio = new Audio('sounds/machine-002-short.mp3');
    var audio2 = new Audio('sounds/coin-drop-4.mp3');

    audio.play();
    audio.volume = 0.65;
    audio.currentTime = 0.90;

    audio2.pause();
    audio.addEventListener("ended", function() {
      audio2.play();
      audio2.volume = 1.5;
      getContent();
    }); // event listener

    $('#odometer').val(<?php echo $Display;?>);
  }, 1000);
}
<form id="form1" action="somefile.php">
  <textarea id="odometer"></textarea>
  <button type="button" id="but">Start</button>
</form>

Upvotes: 1

Related Questions