title: Sleep in Node.js
body: <p>Assumed that there is no &quot;native&quot; way to achieve this, my solution-like was</p>
  <pre><code>sleep = function(time) {
          var stop = new Date().getTime();
          while(new Date().getTime() &lt; stop + time) {
              ;
          }
          return new Promise((r,_)=&gt; r())
        }
  </code></pre>
  <p>So doing <code>sleep(1000*3).then(()=&gt;console.log(&quot;awake&quot;))</code> it will sleep 3 seconds and then resolve the <code>Promise</code>:</p>
  <p>(be aware that it will freeze this page one sec.)</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>sleep = function(time) {
    var stop = new Date().getTime();
    while (new Date().getTime() &lt; stop + time) {;
    }
    return new Promise((r, _) =&gt; r())
  }
  console.log("sleeping...")
  sleep(1000 * 1).then(() =&gt; console.log("awake"))</code></pre>
  </div>
  </div>
  </p>
  <p>Assumed that this will run in the main thread it will freeze the main process so that doing</p>
  <pre><code>sleep(1000*1).then(()=&gt;console.log(&quot;awake&quot;)); console.log(&quot;Hello&quot;)
  </code></pre>
  <p>it will result in a output</p>
  <pre><code>VM2628:1 Hello
  VM2628:1 awake
  </code></pre>
  <p>at very end of the sleep. Of course doing</p>
  <pre><code>setTimeout(()=&gt;sleep(1000*3).then(()=&gt;console.log(&quot;awake&quot;)),1000);console.log(&quot;Hello&quot;)
  VM2815:1 Hello
  undefined
  VM2815:1 awake
  </code></pre>
  <p>will make it async, but it does not address my need (to put to <code>sleep</code> my main process).
  Any better way?</p>
  <p><strong>[UPDATE]</strong>
  Promisified version</p>
  <pre><code>/**
   * Sleep for time [msec]
   * @param time int milliseconds
   * @return Promise delayed resolve
   * @usage
      sleep(1000*3).then(()=&gt;console.log(&quot;awake&quot;))
   */
  sleepP: function (time) {
    return new Promise((resolve, reject) =&gt; {
      var stop = new Date().getTime();
      while (new Date().getTime() &lt; stop + time) {
        ;
      }
      return resolve(true)
    });
  }
  </code></pre>
  <p>that can be called like</p>
  <pre><code>await sleepP( 1000 * 3 );
  </code></pre>