单击事件处理程序后,如何停止我的Javascript代码?

时间:2016-03-23 11:53:56

标签: javascript

所以我的hmtl eventhandeling按钮是

<input type="button" value="Stop" onclick="stop()">

和javascript函数stop()是:

function stop()
{
    stop.called = true;
}

我在这里调用这个函数:

....
var interval = setInterval(function () 
{
    // call generation again for each generation, passing in the previous generations best offspring
    best_offspring = generation(best_offspring, characters, amount_offspring, mutation_rate, target_text);
    document.getElementById("output_text").value = best_offspring;
    document.getElementById("generations").value = generations;
    if (score_met) 
    {
        clearInterval(interval);
    }
}, delay);

if (stop.called)
{
    return;
}

// so that we know that the program has been run atleast once
start = true;
}

您需要更多代码吗?

无论如何,我想要的是在调用函数时停止执行。但即使调用了interval函数,我的stop()循环也会继续。我也尝试过'if(stop.called)inside var interval`循环。但那也没有用。

有什么想法吗?我需要提供更多信息吗?

3 个答案:

答案 0 :(得分:1)

if (stop.called)
{
    clearInterval(interval);
}

¿?

答案 1 :(得分:0)

rails my(r);

答案 2 :(得分:0)

SetInterval返回一个Id,因此您只需调用clearInterval(id);.返回中断等不起作用,因为它实际上并不是像for和while那样的循环。