[nodejs]异步sleep和同步sleep(Asynchronous/Synchronous )

同步睡眠(Synchronous Sleep

方式1:

setTimeout(function () {
  clearInterval(i);
  console.log('end');
}, 100000);

var i = setInterval(function () {
  console.log('ping');
}, 1000);

方式2:

var i = setInterval(function () {
  console.log('ping');
}, 1000);

sleep(100000);

 

异步睡眠(Asynchronous Sleep)
安装deasync:

https://www.npmjs.com/package/deasync

function SyncFunction(){
  var ret;
  setTimeout(function(){
      ret = "hello";
  },3000);
  while(ret === undefined) {
    require('deasync').sleep(100);
  }
  // returns hello with sleep; undefined without
  return ret;    
}

猜你喜欢

转载自aigo.iteye.com/blog/2275008