js sleep方法,延时启动

js使用setTimeout来延时,但是如果你想延时多次就需要嵌套多个setTimeout,非常麻烦。下面是js实现的sleep函数,延时起来更加方便:

  const sleep = async (time) => {
    
    
    var p = new Promise((resolve, reject) => {
    
    
      setTimeout(() => {
    
    
        console.log(666, "click btns done.");
        resolve();
      }, time);
    });
    return p;
  };

下面是如何使用:

f = async() => {
    
    
	console.log(1)
	await sleep(1000) //1s以后
	console.log(2)
}

猜你喜欢

转载自blog.csdn.net/HGGshiwo/article/details/128570339