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