简体   繁体   English

每次运行,JavaScript函数都会循环两次

[英]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. 我正在尝试在JavaScript(+ JQuery)中使用类似于声音校准器系统的功能。 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 system 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. 从testFreqNum警报中,我可以看到它第一次添加1,第二次添加1然后再次添加,第三次添加4次,然后8次。

Probably an easy error to fix - I'm new to JavaScript so maybe you can see it straight away? 可能是一个容易解决的错误-我是JavaScript新手,所以也许您可以立即看到它? 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: 每次都要绑定一个附加的单击处理程序,如果要更改它,只需.unbind() ,如下所示:

 $('#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. ...与#no相同,否则,每次调用.click()您都将附加一个新的click事件处理程序,但不会删除前一个事件处理程序,因此都将被执行...并每次都添加一个附加的处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM