TypeScript 中是否有秒表的任何实现?

Ali*_*iuk 3 stopwatch typescript

我想在用TypeScript编写的网站上运行一些关键功能的性能测量。我想知道在TypeScript 中是否有类似于 .NET类的秒表实现?System.Diagnostics.Stopwatch

sea*_*ass 9

基于basarat上面的答案,这已经内置到console中。

console.time('myTask');
// code to time here
console.timeLog('myTask');
console.timeEnd('myTask');
Run Code Online (Sandbox Code Playgroud)


bas*_*rat 6

在这里有一个简单的实现:

/**
 * Simple timer
 */
export function timer() {
    let timeStart = new Date().getTime();
    return {
        /** <integer>s e.g 2s etc. */
        get seconds() {
            const seconds = Math.ceil((new Date().getTime() - timeStart) / 1000) + 's';
            return seconds;
        },
        /** Milliseconds e.g. 2000ms etc. */
        get ms() {
            const ms = (new Date().getTime() - timeStart) + 'ms';
            return ms;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

const howLong = timer();
// do some stuff
console.log(howLong.ms);
Run Code Online (Sandbox Code Playgroud)

还有许多其他实现以及console.time您可以查看的内置函数。