0

I need a non-interfering time delay in javascript. Specifically, I need something like:

console.log("A");
someSortOfSleepFunction(3000);
console.log("B");
console.log("C");

with the three-second sleep actually occuring between "A" and "B", i.e.

A
wait
B
C

If I use:

console.log("A");
setTimeout(function(){ console.log("B"); }, 3000);
console.log("C");

what I get, of course, is:

A
C
wait
B

I wrote a sleep function, i.e.

function mdjSleep(n) {

    var sleepStart;
    var sleepEnd;
    var sleepNow;

    sleepStart = new Date().getTime();
    sleepEnd = sleepStart + n;

    while(true) {
        sleepNow = new Date().getTime();
        if (sleepNow >= sleepEnd) {
            break;
        }
    }
}

but it interferes, i.e., when I code:

console.log("A");
mdjSleep(3000);
console.log("B");
console.log("C");

instead of

A
wait
B
C

it produces:

wait
A
B
C

Any suggestions?

mdavidjohnson
  • 121
  • 10
  • 1
    Closest equivalent in js to what you're looking for is [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await). – Daniel Beck Jul 26 '18 at 19:02
  • Your `mdjSleep` function works actually. The only problem is that it blocks everything, including the buffered console from displaying the already logged `A` line. – Bergi Jul 26 '18 at 19:06

0 Answers0