Hi, I was wondering how you can yield a while loop until, let’s say, a button is pressed. Example:
“`javascript while (true) { console.log(“While loop thing happened”) – waitUntil(button.onclick) // this isn’t an actual function, but something like that. } “`
@SempervivumDec 13.2021 — #A real endless loop in JS is not appropriate as it would freeze the browser. However you might implement it by use of setTimeout :
HTML: ``<i> </i> <button id = "stop-btn"> Stop</ button><i> </i>`</CODE> JS: <CODE>`<i> </i> const intv = 100; let cont = true; function delayAction() { console.log('action'); if (cont) { setTimeout(delayAction, intv); } } delayAction(); document.getElementById('stop-btn').addEventListener( 'click', event = > { cont = false; });<i> </i>`</CODE> However I'm not really sure if this is what you require. When I take a look at your previous thread something like this comes to my mind:<br/> HTML: <CODE>`<i> </i> <button id = "next-btn"> Next !</ button><i> </i>`</CODE> JS: <CODE>` <i> </i>const intv = 100; const snapshot = [ 1, 2, 4, 8 ]; // just for testing let helperArr = []; snapshot.forEach(function(item) { helperArr.push(item); }); function *gen(arr) { for (let item of arr) { // return item and wait for next request: yield item; } } const g = gen(helperArr); document.getElementById('next-btn').addEventListener('click', event = > { // get next item: const result = g.next(); // no more items left? if (result.done) { console.log('no more values'); } else { console.log('current value = ' + result.value); } });<i> </i>`` Does any of these meet your requirement ?
I think a better way to handle this would be the use of a timer. This would allow the form to draw its controls and handle all input, such as clicking the button. You can also adjust the timer interval (ms) to your needs.
Another way is to use multi-threading. I would strongly recommend condition checks over the try/catch checks if possible. Enable/Disable the timer using the button and call the loop when the timer ticks. [Here is](https://www.eleken.co/saas-web-design) an example I put in my project: