durations中文文档|durations js中文教程|解析

npm npmdoc 2年前 (2022-01-02) 391次浏览

durations中文文档|durations js中文教程|解析

安装命令:npm i durations

durations

构建状态
NPM 版本

兼容性

Node.js 和浏览器都支持durations使用 Node.js 时,使用纳秒粒度process.hrtime()函数。在浏览器中选择最佳替代,这样即使时间粒度不能保持一致性。

安装

npm install --save durations

方法

导出以下函数:

  • duration(nanoseconds) – 构建一个新的持续时间
  • nanos(nanoseconds) – 构建一个新的持续时间
  • micros(microseconds) – 构建一个新的持续时间
  • millis(milliseconds) – 构建一个新的持续时间
  • seconds(seconds) – 构建一个新的持续时间
  • stopwatch() – 构建一个新的秒表(停止)
  • time(function) – 同步时间函数
  • timeAsync(function(callback)) – 异步时间函数
  • timePromised(function()) – 次承诺返回函数

期间

表示纳秒粒度的持续时间,并提供转换为其他粒度的方法,以及格式化持续时间的方法。

方法

  • format() – 表示持续时间的人类可读字符串
  • nanos() – 持续时间为纳秒
  • micros() – 持续时间为微秒
  • millis() – 以毫秒为单位的持续时间
  • seconds() – 持续时间为秒
  • minutes() – 持续时间为分钟
  • hours() – 持续时间为小时
  • days() – 持续时间为天
const {duration} = require('durations')
 
const nanoseconds = 987654321
console.log("Duration is", duration(nanoseconds).format())
 
// Or, since toString() is an alias to format()
console.log(`Duration is ${duration(nanoseconds)}`)

跑表

具有可链接控制方法和内置格式的纳秒粒度(在 Node.js 上)秒表。

秒表方法

  • start() – 启动并返回秒表(如果已经运行则无操作)
  • stop() – 停止并返回秒表(如果不运行则无操作)
  • reset() – 将经过时间重置为零并返回秒表(意味着停止)
  • duration() – 获取经过的时间作为持续时间
  • isRunning()– 正在运行的秒表 ( true/ false)
const {stopwatch} = require('durations')
const watch = stopwatch()
 
// Pauses the stopwatch. Returns the stopwatch.
watch.stop()
 
// Starts the stopwatch from where it was last stopped. Returns the stopwatch.
watch.start()
 
// Reset the stopwatch (duration is set back to zero). Returns the stopwatch.
watch.reset()
 
console.log(`${watch.duration().seconds()} seconds have elapsed`)
// OR
console.log(`${watch} have elapsed`)

定时器

对函数的执行进行计时,并返回持续时间。

const {time: timeSync, timeAsync} = require('durations')
 
// Synchronous work
const someFunction = () => {
  let count = 0
 
  while (count < 1000000) {
    count++
  }
 
  console.log(`Count is: ${count}`)
}
 
console.log(`Took ${timeSync(someFunction)} to do something`)
 
// Asynchronous work
const someOtherFunction = next => {
  someFunction()
  next()
}
 
timeAsync(someOtherFunction, duration => {
  console.log(`Took ${duration} to do something else.`)
})
 
// Promised work
const somePromisedOp = () => {
  return new Promise((resolve) => {
    someFunction()
    resolve()
  })
}
 
timePromised(somePromisedOp)
.then(duration => {
  console.log(`Took ${duration} to keep promise.`)
})
项目贡献人员列表:


极客公园 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:durations中文文档|durations js中文教程|解析
喜欢 (0)
.excerpt .focus {display:none}