0

Here is what I'm trying to achieve:

console.log("Line at the start");
sleepFunction(5000);
console.log("Line printed after 5 seconds");

Output:

Line at the start
<waits for 5 seconds>
Line printed after 5 seconds

Is there any function like this? I've tried to use setInterval but the line printed after 5 seconds appears first, then it waits for 5 seconds.

Yash Patil
  • 33
  • 1
  • 4

1 Answers1

-1

As mentioned in the comments you can use asynchronous code

function sleep(msec) {
    return new Promise(resolve => setTimeout(resolve, msec))
}

async function print() {
    console.log("Line at the start")
    await sleep(5000);
    console.log("Line printed after 5 seconds")
}

print();

Or use only setTimeout and print the second line in the callback that gets invoked after 5 seconds

function print2() {
    console.log("Line at the start2")
    setTimeout(() => {
        console.log("Line printed after 5 seconds2")
    }, 5000)
}

print2()
Diogo Santos
  • 49
  • 1
  • 5