2016-03-23 3 views
0

So ist meine HMTL eventhandeling TasteWie kann ich meinen Javascript-Code stoppen, nachdem auf einen Event-Handler geklickt wurde?

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

und die JavaScript-Funktion stop() ist:

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

und ich nenne diese Funktion hier:

.... 
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; 
} 

Brauchen Sie mehr des Codes ?

Wie auch immer, ich möchte die Ausführung stoppen, wenn die Funktion aufgerufen wird. Aber meine interval-Schleife wird fortgesetzt, obwohl die stop()-Funktion aufgerufen wird. Ich habe auch versucht, die'if (stop.called) inside var interval'-Schleife zu setzen. Aber das hat auch nicht funktioniert.

Irgendwelche Ideen? Muss ich mehr Informationen zur Verfügung stellen?

Antwort

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

Versuchte dies, funktionierte nicht, bis ich das 'if (stop.called)' innerhalb der 'setInterval'-Funktion setzte. Warum? –

0

SetInterval liefert eine ID, so dass Sie einfach clearInterval (id) nennen kann ;. Return Break usw. funktioniert nicht, weil es nicht wirklich eine Schleife wie für und während ist.

Verwandte Themen