当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。