3

How would I convert the following:

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

into JavaScript?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
David542
  • 104,438
  • 178
  • 489
  • 842
  • http://stackoverflow.com/questions/951021/what-do-i-do-if-i-want-a-javascript-version-of-sleep – l4mpi Jan 14 '13 at 22:11
  • 1
    Think about what this does in Python: The whole program just sits around and does nothing while you're `sleep`ing. 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 Jan 14 '13 at 22:14
  • @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 Jan 14 '13 at 22:16
  • @David542: I'd suggest you do it exactly the way Bergi's answer shows. That's pretty much why these functions exist. – abarnert Jan 14 '13 at 22:19

2 Answers2

10

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();
abarnert
  • 354,177
  • 51
  • 601
  • 671
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • "it is synchronous and event-based" - by that you mean _a_synchronous, right? –  Jan 14 '13 at 22:13
  • 1
    @Brian: Let's say "On each asynchronous event a synchronous, single-threaded execution takes place" – Bergi Jan 14 '13 at 22:18
  • +1. But it may be worth mentioning that if "do something" takes, say, 1 second, `setInterval` may call it at 0, 2, 4, 8, 10, … seconds, while the OP's Python code would run at 0, 3, 6, 9, 12, … seconds. (To do that, you can use `setTimeout` and schedule a new `setTimeout` at the end of the callback.) – abarnert Jan 14 '13 at 22:21
  • Nice way to handle my suggestion—better than I would have come up with. Too bad I already gave you a +1 and can't give another. – abarnert Jan 14 '13 at 22:34
0
setInterval(function() {
  console.log('do something');
}, 2000);

http://jsfiddle.net/rS9bH/

Demian Brecht
  • 21,135
  • 5
  • 42
  • 46