JS 实现一个睡眠函数sleep


睡眠函数

比如 sleep(1000)代表等待 1000ms

方法一:ES5 方式实现

function sleep(callback, time) {
  if (typeof callback == "function") {
    setTimeout(callback, time);
  }
}
function output() {
  console.log(1);
}
sleep(output, 2000);

方法二:使用 promise 方式

const sleep = (time) => {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
};
sleep(2000).then(() => {
  console.log(1);
});

方法三:利用 async

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

async function init() {
  var temp = await sleep(2000);
  console.log("YJJ"); //2s后执行
}

init();


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM