JavaScript function loops twice as many times every time ran
I'm trying to use a function in JavaScript (+JQuery) which is like a sound calibrator system. It starts at one frequency band, plays it, asks the user if they can hear it - then if the can it knows the lowest frequency of their sys开发者_运维知识库tem and if not it goes up to the next band and then re-checks etc. until the lowest frequency is found.
However, when I run the function, it seems to run itself twice as many times each time. From the testFreqNum alert I could see the first time it added 1 once, the second time it added 1 then added it again, third time it did it 4 times, then 8 etc.
Probably an easy error to fix - I'm new to JavaScript so maybe you can see it straight away? Thanks.
function testFreq(band, testType){
if (testType == 'testLow') {
$('#calibrationText').html('<h5>Testing ' + freqs[band] + 'Hz...</h>');
playSound('Tones', band);
//window.setTimeout(function(){
$('#calibrationText').html('<h5>Could you hear ' + freqs[band] + 'Hz clearly?</h>');
$('#yes').fadeIn(500).click(function(){
bandMin = band;//sets randGen's min availible band value
testFreqNum = 31;//sets test frequency to upper high
testFreq(testFreqNum, 'testHigh');//runs calibrator again in high mode starting band 31
$('#yes').fadeOut(500);
$('#no').fadeOut(500);
});
$('#no').fadeIn(500).click(function(){
testFreqNum = testFreqNum + 1;
alert(testFreqNum);
testFreq(testFreqNum, 'testLow');//runs calibrator again in low mode
//$('#yes').fadeOut(500);
//$('#no').fadeOut(500);
});
// }, 4000);
}
...and the rest...
You're binding an additional click handler each time, if you want to change it, just .unbind()
first, like this:
$('#yes').fadeIn(500).unbind("click").click(function(){
...and the same for #no
, otherwise each time you call .click()
you're attaching a new click
event handler, but not removing the previous one, so both get executed...and an additional one added each time.
精彩评论