當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


HTML DOM console.time()用法及代碼示例


HTML中的console.time()方法用於在控製台視圖中啟動計時器。 console.time()方法可用於計算各種測試目的的程序時間。標簽將作為參數發送到console.time()方法。

用法:

console.time( label )

參數:此方法接受單個參數標簽,該標簽是可選的,用於指定計時器的標簽。


以下程序說明了HTML中的console.time()方法:

範例1:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>DOM console.time() Method in HTML</title> 
    <style> 
        h1 { 
            color:green; 
        } 
          
        h2 { 
            font-family:Impact; 
        } 
          
        body { 
            text-align:center; 
        } 
    </style> 
</head> 
  
<body> 
    <h1>GeeksforGeeks</h1> 
    <h2>DOM console.time() Method</h2> 
    <p> 
      To view the message in the console 
      press the F12 key on your keyboard. 
    </p> 
    <p> 
      To view the time taken by a for loop 
      to run 100 times, double click the  
      button below:
    </p> 
    <br> 
    <button ondblclick="table_time()"> 
      RUN TIMER 
    </button> 
    <script> 
        function table_time() { 
            console.time(); 
            for (i = 0; i < 100; i++) { 
                // Random code 
            } 
            console.timeEnd(); 
        } 
    </script> 
</body> 
  
</html>   

輸出:

控製台視圖:

範例2:使用console.time()方法計算while循環所花費的時間

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>DOM console.time() Method in HTML</title> 
    <style> 
        h1 { 
            color:green; 
        } 
          
        h2 { 
            font-family:Impact; 
        } 
          
        body { 
            text-align:center; 
        } 
    </style> 
</head> 
  
<body> 
    <h1>GeeksforGeeks</h1> 
    <h2>DOM console.time() Method</h2> 
    <p> 
      To view the message in the console 
      press the F12 key on your keyboard. 
    </p> 
    <p> 
      To view the time taken by a for loop 
      to run 100 times, double click the 
      button below:
    </p> 
    <br> 
    <button ondblclick="table_time()"> 
      RUN TIMER 
    </button> 
    <script> 
        function table_time() { 
            i = 0; 
            console.time 
                ("While loop for 100 iterations"); 
            while (i < 100) { 
                i++; 
            } 
            console.timeEnd 
                ("While loop for 100 iterations"); 
        } 
    </script> 
</body> 
  
</html>

輸出:

控製台視圖:

支持的瀏覽器:console.time()方法支持的瀏覽器如下:

  • 穀歌瀏覽器
  • Internet Explorer 11.0
  • Firefox 10.0
  • Opera
  • Safari 4.0


相關用法


注:本文由純淨天空篩選整理自Shubrodeep Banerjee大神的英文原創作品 HTML | DOM console.time() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。