[JS] console.time() - 計時器建構函式及如何計時

來源:互聯網
上載者:User

標籤:style   blog   color   使用   io   for   art   ar   

概述

  使用計時器可以對代碼運行過程進行測速。你可以給每個計時器取一個名字,每個頁面上最多可以運行一萬個計時器。當你使用計時器名字調用 console.timeEnd() 函數時,瀏覽器會返回一個毫秒值,該值表示該計時器啟動到你調用 console.timeEnd() 時的時間。

 

文法
console.time(timerName);

 

timerName

  計時器名稱,該名稱用於標識一個計時器,當使用該名稱調用 console.timeEnd() 時會停止相應的計時器,並在控制台輸出計時時間。

 

如何捕獲計時器傳回值

  很可惜,console.time() 和 console.timeEnd() 只能在控制台輸出計時時間,但不能返回輸出內容,也就不能賦給變數儲存。

  如果需要計時作為變數使用,可以使用 window.performance.now() 函數計時:

var start = window.performance.now();var end = window.performance.now();var duration = end - start;

  

  window.performance.now() 返回一個浮點值表示當前距離頁面被載入時的毫秒時間,如果想知道頁面是何時被載入的,可以擷取 window.performance.timing.navigationStart 值,該表示頁面載入時的 Unix 時間戳記。

 

  你也可以使用 Date.now() 函數來計時,該函數返回一個整數毫秒值。

var start = Date.now();var duration = Date.now() - start;

 

  又或者 Date().getTime() 對象計時,該對象返回的是 Unix 時間戳記:

var start = new Date().getTime();var end = new Date().getTime();var duration = end - start

 

  PS:window.performance.now() 會比 Date.now() 慢很多。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.