What is the JavaScript equivalent of sleep(), and how can I implement an actual pause in code execution?

I’m looking for a real javascript sleep function that halts execution in the middle of a function not just a delay before a callback runs.

I came across this pausecomp function:

function pausecomp(millis) {
    var date = new Date();
    var curDate = null;
    do { curDate = new Date(); }
    while(curDate - date < millis);
}

What and how is the best way to simulate a true sleep behavior in JavaScript, ideally without blocking the main thread?

If you’re working in an async function, this version of sleep feels pretty close to what you’d find in Python or Java. I use it a lot in automation scripts and it works like a charm:

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

// Usage in async function
async function demo() {
  console.log('Waiting...');
  await sleep(2000); // Waits for 2 seconds
  console.log('Done!');
}

demo();

The pausecomp() function you found is basically a busy wait loop. It does pause execution, but it blocks the entire browser thread while doing so:

function pausecomp(millis) {
  const date = new Date();
  let curDate = null;
  do { curDate = new Date(); }
  while(curDate - date < millis);
}

It does work, but it’s like hitting the brakes on your app. Your UI freezes, animations stop, and users can’t interact with anything while it’s running.

Great for testing or niche uses, but not for real-world applications.

If you’re not in an async context and just want to delay the next step, a classic setTimeout() still does the job:

console.log('Start');
setTimeout(() => {
  console.log('This runs after 2 seconds');
}, 2000);
console.log('End');

It won’t pause execution inline like sleep(), it schedules the next part to happen later. So anything after setTimeout runs immediately unless wrapped in the callback.