I have a code which needs to be executed after some delay say 5000 ms.Currently I am using setTimeout but it is asynchronous and i want the execution to wait for its return. I have tried using the following:

function pauseComp(ms) 
     var curr = new Date().getTime();
     ms += curr;
     while (curr   < ms) {
         curr = new Date().getTime();

But the code i want to delay is drawing some objects using raphaeljs and the display is not at all smooth. I am trying to use doTimeout plugin. I need to have a delay only once as the delay and code to be delayed are both in a loop. I have no requirement for a id so I am not using it. For example:

for(i; i<5; i++){ $.doTimeout(5000,function(){
         alert('hi');  return false;}, true);}

This waits for 5 sec befor giving first Hi and then successive loop iterations show alert immediately after the first. What I want it to do is wait 5 sec give alert again wait and then give alert and so on.

Any hints/ suggestions are appreciated!

10 Answers 10


Variation on the accepted answer which is just as good as this one.

Also, I agree with the caveats of preferring setTimeout and asynchronous function calling but sometimes e.g., when building tests, you just need a synchronous wait command...

function wait(ms) {
    var start = Date.now(),
        now = start;
    while (now - start < ms) {
      now = Date.now();

if you want it in seconds, divide start ms by 1000 on the while check...

  • 7
    Just watch out for CPU use. – Joseph Lust Mar 14 '18 at 17:58
  • 3
    Definitely, @JosephLust. Another reason why it should only be used for tests and not production code. – ThinkBonobo Mar 16 '18 at 17:51

If you'd like to take advantage of the new async/await syntax, You can convert set timeout to a promise and then await it.

function wait(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Done waiting");
    }, ms )

(async function Main() {
  await wait(5000);

Synchronous wait (only for testing!):

const syncWait = ms => {
    const end = Date.now() + ms
    while (Date.now() < end) continue



Asynchronous wait:

const asyncWait = ms => new Promise(resolve => setTimeout(resolve, ms))


(async () => {
    await asyncWait(5000)

Alternative (asynchronous):

const delayedCall = (array, ms) =>
    array.forEach((func, index) => setTimeout(func, index * ms))


    () => console.log('one'),
    () => console.log('two'),
    () => console.log('three'),
], 5000)

JavaScript is a single-threaded language. You cannot combine setTimeout and synchronous processing. What will happen is, the timer will lapse, but then the JS engine will wait to process the results until the current script completes.

If you want synchronous methods, just call the method directly!

If you want to process something after the setTimeout, include it or call it from the timeout function.


Using the new Atomics API, you can start synchronous delays without performance spikes:

const sleep = milliseconds => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds)

sleep(5000) // Sleep for 5 seconds

console.log("Executed after 5 seconds!")
  • This has the very beneficial effect of using an optimized thread sleep (instead of busy waiting), so the CPU can idle for the synchronous sleep duration instead of crunching a loop. However, keep in mind that the current specification does not allow Atomics.wait to be used on the main thread, only worker threads. – John Weisz Dec 16 '20 at 14:23

Non-timeout loops (that check the time or count to 1000000 or whatever) just lock up the browser. setTimeout (or the $.doTimeout plugin) is the best way to do it.

Creating timeouts within a loop won't work because the loop doesn't wait for the previous timeout to occur before continuing, as you've discovered. Try something more like this:

// Generic function to execute a callback a given number
// of times with a given delay between each execution
function timeoutLoop(fn, reps, delay) {
  if (reps > 0)
    setTimeout(function() {
                 timeoutLoop(fn, reps-1, delay);
               }, delay);

// pass your function as callback
timeoutLoop(function() { alert("Hi"); },

(I just cobbled this together quickly, so although I'm confident that it works it could be improved in several ways, e.g., within the "loop" it could pass an index value into the callback function so that your own code knows which iteration it is up to. But hopefully it will get you started.)

  • 1
    Beside setTimeout is a better option, the OP request a syncronous method. @ThinkBonobo answered correctly – robsonrosa Mar 20 '17 at 14:12
  • 1
    @robsonrosa - The OP also said "the code i want to delay is drawing some objects using raphaeljs and the display is not at all smooth". You can't use synchronous code and draw things, because the screen won't be repainted until the synchronous code completes. Just because the OP asked for something doesn't make it possible. – nnnnnn Mar 20 '17 at 21:03
  • 1
    The user is specifically looking for a synchronous solution - setTimeout is not synchronous – Drenai Apr 18 '18 at 14:34
  • @Ryan - As per my previous comment, just because they asked for something doesn't make it possible. A synchronous delay can't coexist with the drawing they're doing, which they complained is not smooth enough. – nnnnnn Apr 18 '18 at 22:46

I have made a simple synchronous timeout function. It works in two different ways, callback and non-callback.


function wait(ms, cb) {
  var waitDateOne = new Date();
  while ((new Date()) - waitDateOne <= ms) {
  if (cb) {

callback example:


non-callback example:

console.log("5 second delay");
  • 3
    Use cb() instead of eval(db). Saving script in a string is not a good practice. Usage: wait(5000, function(){console.log("test!")}). BTW, it's better to use setTimeout if you need callback – user5147563 Nov 26 '17 at 19:14
  • I think use requestAnimationFrame(function(){}) maybe better than nothing in while loop, and doing nothing in while loop will cost much cpu. – gogog May 7 '20 at 11:58

Here's how you can use the JQuery doTimeout plugin

jQuery('selector').doTimeout( [ id, ] delay, callback [, arg ... ] );

From the docs: "If the callback returns true, the doTimeout loop will execute again, after the delay, creating a polling loop until the callback returns a non-true value."

var start = Date.now();
console.log("start: ", Date.now() - start);
var i = 0;
$.doTimeout('myLoop', 5000, function() {
  console.log(i+1, Date.now() - start);
  return i == 5 ? false : true;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dotimeout/1.0/jquery.ba-dotimeout.min.js"></script>


Solution using function generators. To show that it can be done. Not recommended.

function wait(miliseconds){

  const gen = function * (){
     const end = Date.now() + miliseconds;
     while(Date.now() < end){yield};
  const iter = gen();
  while(iter.next().done === false);

console.log("done 0");
console.log("done 1");
console.log("done 2");

  • This generator function makes no sense, it could trivially be inlined. This is just the same solution as in the other answers, but unnecessarily complex. – Bergi Jan 22 '19 at 20:25
  • @Bergi Thanks for your opinion. I wouldn't agree with unnecessarily complex though. It's the same argument when async/await is done with function generators; a complex wrapper just to use function generators with an underlying async/await and yet it's widely used. – kemicofa ghost Jan 22 '19 at 20:29
  • 1
    This has nothing to do with async/await or running user-supplied generators in a specific way - it's not even asynchronous. It's a local function inside wait, and deserves to be simplified. There is absolutely no advantage in using generators here - the only difference is that it burns the CPU cycles on different instructions. – Bergi Jan 22 '19 at 20:32

Node solution

Use fs.existsSync() to delay

const fs = require('fs');
const uuidv4 = require('uuid/v4');

 * Tie up execution for at-least the given number of millis.  This is not efficient.
 * @param millis Min number of millis to wait
function sleepSync(millis) {
    if (millis <= 0) return;
    const proceedAt = Date.now() + millis;
    while (Date.now() < proceedAt) fs.existsSync(uuidv4());

fs.existsSync(uuidv4()) is intended to do a few things:

  1. Occupy the thread by generating a uuid and looking for a non-existent file
  2. New uuid each time defeats the file system cache
  3. Looking for a file is likely an optimised operation that should allow other activity to continue (i.e. not pin the CPU)
  • If you down vote, please explain why. I find this technique to be effective but if it's wrong I really want to know why. I expect fs.existsSync() to not pin the CPU which is beneficial. – Peter L Jun 5 '20 at 17:23
  • You don't explain what uuid/v4 is used for. As a beginner to Javascript, I'd like to know what each piece of the code does and why it works for you. – Jonathin Jun 16 '20 at 7:36
  • Thanks @jramos775, I see now it wasn't very obvious. – Peter L Jun 17 '20 at 19:09

Your Answer

