Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python while loop conversion to Javascript [duplicate]

How would I convert the following:

while True:
    # do something
    time.sleep(2)

into JavaScript?

like image 633
David542 Avatar asked Jul 14 '26 10:07

David542


1 Answers

You would not, as JavaScript does not sleep - it is synchronous and event-based. Yet, you can schedule functions to be executed later in time via setTimeout and setInterval:

var timerid = setInterval(function() {
    // do something
    // instead of "break", you'd use "clearTimeout(timerid)"
}, 2000);

For your ajax progress bar, I'd recommend the following which does not fire requests strictly each 2s, but waits for them to return:

function getUpdate() {
    myAjax(…, function onAjaxSuccess(result) { // an async event as well
        // show(result)
        if (!result.end)
            setTimeout(getUpdate, 2000);
    });
}
getUpdate();
like image 79
Bergi Avatar answered Jul 22 '26 17:07

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!