美文网首页
js 实现sleep函数

js 实现sleep函数

作者: 指尖跳动 | 来源:发表于2020-02-17 23:42 被阅读0次

实现如下效果:

//输出1,2秒后输出2
console.log(1)
sleep(2000)
console.log(2)

方法一:

function sleep(delay) {
  var start = (new Date()).getTime();
  while ((new Date()).getTime() - start < delay) {
    continue;
  }
}

function test() {
  console.log('111');
  sleep(2000);
  console.log('222');
}

test()

方法二:

async function test() {
  console.log('Hello')
  await sleep(1000)
  console.log('world!')
}

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

test()

相关文章

网友评论

      本文标题:js 实现sleep函数

      本文链接:https://www.haomeiwen.com/subject/sfrwfhtx.html