2016-03-23 7 views
0

だから私のHMTL eventhandelingボタンがイベントハンドラがクリックされたら、JavaScriptコードを停止するにはどうすればよいですか?

<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`ループを入れようとしました。しかし、それはどちらかの仕事でもありませんでした。

アイデア?私はより多くの情報を提供する必要がありますか?

答えて

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

¿? 
0
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 || stop.called) 
    { 
     clearInterval(interval); 
    } 
}, delay); 

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

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

私は 'setInterval'関数の中に' if(stop.called) 'を置くまでこれを試していませんでした。どうして? –

0

のsetIntervalあなたは、単にてclearInterval(id)を呼び出すことができるようにIDを返します;. break breakなどを返します。なぜなら、forやwhileのようなループではないからです。

関連する問題