time delay between 2 lines of code in javascript, not settimeout

The following is clunky and ugly and I would never do it in my own code and I DO NOT RECOMMEND IT AT ALL, but it shows that such a thing is possible.

// time arg is in milliseconds
function delay(time) {
  var d1 = new Date();
  var d2 = new Date();
  while (d2.valueOf() < d1.valueOf() + time) {
    d2 = new Date();
  }
}

In JavaScript 1.7, using yield with async.js, you can do the following:

var yourFunction = _(function () {
    write("abc");
    yield to.sleep(.500);
    write("xyz");
});

You can use setTimeout so that it almost appears the code runs on two lines:

write('abc')
setTimeout(function() {
write('xyz')
},500)

A sleep-Method is not available because JavaScript execution blocks the browser, so a sleep-Method would block the browser for 500msec, do you really want to have your browser not responding for half an second?

Use setTimeout as suggested.

Tags:

Javascript