3
votes

Possible Duplicate:
Sleep in Javascript
What do I do if I want a JavaScript version of sleep()?

How would I convert the following:

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

into javascript?

2
Think about what this does in Python: The whole program just sits around and does nothing while you're sleeping. If you did the same thing in JS, the browser (or node.js server) would also sit around and do nothing, which is bad, because you usually want to be able to, say, scroll around the page or click on links (or handle other users' connections). - abarnert
@abarnert - thanks for pointing this out. I am trying to create a progress bar that would 'refresh' every two seconds with an ajax call to get the progress from the database. How would you suggest I do this? - David542
@David542: I'd suggest you do it exactly the way Bergi's answer shows. That's pretty much why these functions exist. - abarnert

2 Answers

10
votes

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();
0
votes
setInterval(function() {
  console.log('do something');
}, 2000);

http://jsfiddle.net/rS9bH/