Python while loop conversion to Javascript

How would I convert the following:

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

into JavaScript?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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();

Method 2

setInterval(function() {
  console.log('do something');
}, 2000);

http://jsfiddle.net/rS9bH/


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x