源码地址:SchedulerDOM.js文件下的getCurrentTime变量
- 先判断浏览器支不支持
performance,如果支持,就使用performance.now() - 否则就使用
Date.now()
// 提供了一个获取当前时间戳的函数
let getCurrentTime;
// 判断是否支持 performance
const hasPerformanceNow =
typeof performance === 'object' && typeof performance.now === 'function';
if (hasPerformanceNow) {
const localPerformance = performance;
getCurrentTime = () => localPerformance.now();
} else {
// 如果没有,使用Date
const localDate = Date;
const initialTime = localDate.now();
getCurrentTime = () => localDate.now() - initialTime;
}
为什么 performance
- preformance.now()返回一个精确到
毫秒的时间。但是这个毫秒数包含小数点,精度更高 - 返回值是从 time origin之后到当前调用时经过的
时间段(毫秒)。可以理解是从打开浏览器开始,而非Date的从1970年开始的毫秒
// 取值只是例子,主要看到后面有小数点,精度更高
performance.now() // 625520.2000000477
Date.now()
- 返回值:表示自UNIC纪元开始(1970 年 1 月 1 日 00:00:00 (UTC))到当前时间的
毫秒数,只能取到整数
// 取值只是例子,主要看到是取的整数
Date.now() // 1647184964685