I was trying to find a solution to break a heavy time consuming loop.
All I could find did not break a loop but just stop a timer.
And they were overly complicated for nothing.
After, a period of trial and error.
I give you this.
I'm working on a lot a stuff.
If you want to follow my stuff and/or support me.
You can check/register to my website:
https://thinknspeak.net/
For me this code is completely self-explanatory. If you have any questions. The comments are down below.
async function Sleep(ThisLong){
return new Promise(resolve => setTimeout(resolve, ThisLong));
}
var Interupted;
async function DoSomethingheavyOnAsync() {
// DO SOMETHING HEAVY THAT WOULD KILL ANY BROWSER
// NOW SEE IF THAT WORKS
let ThisValue = 0;
// THAT WOULD KILL ANY BROWSER
// BECAUSE THIS IS GONNA TAKE FOREVER.
let ThisBigVal = 9007199254740992;
for(let Testdx = 0; Testdx < ThisBigVal; Testdx++){
ThisValue = Math.floor(Math.random() * (Testdx));
// IF YOU NEED SPEED ALSO
// YOU NEED TO PROPERLY DISTRIBUTE THE SLEEP
// BECAUSE THE SLEEP LET THE ENTIRE MESSAGE QUEUE RUN
// BEFORE COMING BACK.
// YOU CAN ALSO PLAY WITH THE SLEEP TIME.
// ENJOY THE SIMPLICITY
await Sleep(0);
if((Interupted)){
ShowResult.innerText += ("for(loop) Interupted.\n");
ShowResult.innerText += (`ran ${Testdx} loops.\n`);
return ;
}
}
}
function TestInterupt (){
Interupted = false;
ShowResult.innerText = "";
setTimeout(function (){
ShowResult.innerText += ("Attempting to cancel a LOOP.\n");
Interupted = true;
}, 2000);
DoSomethingheavyOnAsync();
}