0

Hello guys I'm looking for a solution for this program:

var i = 0;
function timer(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}
$w.onReady(function () {
    while (i === 0) {
        dosomething();
        timer(1000);
    }
});

export function button5_click(event) {
    i = 1;
}

My question is how can I stop this while with that button function?

3
  • You can't do that. A function can only be stopped with a return or an error. Commented Jul 10, 2020 at 20:33
  • 2
    Any reason you're not using setTimeout or setInterval? Commented Jul 10, 2020 at 20:34
  • No asynchronous effect can stop an infinite synchronous loop. Commented Jul 10, 2020 at 20:56

3 Answers 3

3

You can do this way!

var flag = true;

let i = 0;
function loopFunc() {
    if (flag == true){
    i++;
        console.log( `Do something here ${i}` );
        setTimeout(loopFunc, 100);
    }
}

loopFunc();

function stop(){
    flag = false;
}
<button onclick="stop();">Stop Loop</button>

Sign up to request clarification or add additional context in comments.

Comments

1

You could have a boolean which is checked if true in the while loop and if it true, the while loop will return. Add in an event listener to make that boolean true on click for the button. Don't forget to make the boolean false at the beginning of your script.

Comments

0

Using your code, you could do this

var stopLoop = false; // Add this to your code
var i = 0;
function timer(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}
$w.onReady(function () {
    while (i === 0) {
        if(stopLoop) break;
        dosomething();
        timer(1000);
    }
});

export function button5_click(event) {
    stopLoop = true; // add this to your code
    i = 1; // You can comment this out
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.