-1

This code works to fade and loop an audio element when a button is pressed:

$("#loop").click(function(){
    var tone = document.getElementById("testTone");
    tone.play();
    $("#testTone").animate({volume: 0}, 1900);
    setInterval(function(){
        tone.currentTime = 0;
        tone.volume = 1;
        tone.play();
        $("#testTone").animate({volume: 0}, 1900);
    },2000)
});

However, when I name the function, it calls immediately on page load, without pressing the button.

function loopAudio(target){
    var tone = document.getElementById(target);
    tone.play();
    $("#"+target).animate({volume: 0}, 1900);
    setInterval(function(){
        tone.currentTime = 0;
        tone.volume = 1;
        tone.play();
        $("#"+target).animate({volume: 0}, 1900);
    },2000)
};
$("#loop").click(loopAudio("testTone"));

Why? And what is the right way to call this named function?

EDIT: Since passing the parameter calls the function, what is a good workaround strategy to pass in a parameter?

drenl
  • 1,321
  • 4
  • 18
  • 32
  • 1
    because... you called it. If it returned a function that then did the stuff, then it would work as you expected it to. – Kevin B Jun 19 '17 at 21:37
  • 1
    because you are calling it you need your click assignment to be `$("#loop").click(loopAudio);` I suggest you place an attribute on the `#loop` element to specify the tone instead of using an argument. – Steve0 Jun 19 '17 at 21:37

1 Answers1

1

Have you tried:

$("#loop").click(function(){
  loopAudio("testTone");
});
Sergio
  • 792
  • 3
  • 10
  • 35