How to stop or reset the execution of a function?
I tried to add a value with the start number to the "while(true)" and return if the number of the launched eval does not match "if (RUN != 39629) return;", but it seems to me that this does not always work correctly. I would like to somehow reliably stop the execution of a running eval.
let a = 0;
let code = `while(true){
await sleep(1000);
cons('step:'+a);
a++;
}`;
$('span').click(e => {
if ($(e.target).text() == 'start') {
cons('start');
eval("(async () => {" + code + "})()");
}
});
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function cons(s)
{
$('div').html($('div').html()+ s +'<br>');
}
span { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>start</span> <span>stop</span>
<div>...<br></div>