Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

day-01-sleep函数 #1

Open
H246802 opened this issue Nov 21, 2018 · 3 comments
Open

day-01-sleep函数 #1

H246802 opened this issue Nov 21, 2018 · 3 comments

Comments

@H246802
Copy link
Owner

H246802 commented Nov 21, 2018

写一个 execTime 函数要求如下
参数:时间毫秒数
作用:什么都不做,但函数执行消耗的时间为参数传递的毫秒数

function execTime(t) {
  // 补全代码
}
console.log(1) // print 1
execTime(3000) // execute cost 3s
console.log(2) // print 2
@H246802
Copy link
Owner Author

H246802 commented Nov 21, 2018

方法一、while循环时间戳

// while循环中判断条件,条件表达式,在每次循环前被求值。
// 如果求值为真,statement就会被执行。如果求值为假,则跳出while循环执行后面的语句。
function execTime(t) {
  var start = (new Date()).getTime()
  while ((new Date()).getTime() - start < t) {
    continue
  }
}
console.log(1)
execTime(3000)
console.log(2)

@H246802
Copy link
Owner Author

H246802 commented Nov 21, 2018

方法二、async、await以及promise,将异步代码变同步

async function asyncCall(time) {
  console.log('1');
  var result = await resolveAfterDelay(time);
  console.log('2');
}

function resolveAfterDelay(time) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(), time)
  })
}
asyncCall(3000)

@H246802
Copy link
Owner Author

H246802 commented Nov 22, 2018

方法三、for循环

function execTime(t) {
  var start = (new Date()).getTime()
  for(var i= start; i > (new Date()).getTime() - t ;) {
   
  }
}
console.log(1)
execTime(3000)
console.log(2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant