HTML DOM console.time() 方法

htmlweb developmentfront end technology更新于 2025/9/24 20:28:17

HTML DOM console.time() 方法用于显示执行一段代码所用的时间。这有助于我们分析整段代码或特定代码片段。通过计时代码,您可以提高代码效率。使用可选的 label 参数,您可以在同一页面上创建多个计时器。

语法

以下是 HTML DOM console.time() 方法的语法 −

console.time(label)

其中,label 是一个可选参数,用于为计时器命名。

示例

让我们来看一个 console.time() 方法的示例 −

<!DOCTYPE html>
<html>
<body>
<h1>console.time() Method</h1>
<p>Click the below button to time the for,while and do-while loops for 100000 iterations </p>
<button type="button" onclick="LoopPerform()">TIMER</button>
<script>
   var i,j,k;
   i=0,j=0,k=0;
   function LoopPerform(){
      console.time("for-loop");
      for (; i < 100000; i++){}
         console.timeEnd("for-loop");
      console.time("while-loop");
      while(j<100000)
         j++;
      console.timeEnd("while-loop");
      console.time("do-while loop");
      do{k++;}
      while(k<100000);
      console.timeEnd("do-while loop");
   }
</script>

Press F12 key to view the performance result in your console view

</body> </html>

输出

这将产生以下输出 −

点击 TIMER 按钮 −

在上面的例子中 −

我们首先创建了一个 TIMER 按钮,当用户点击该按钮时,它将执行 LoopPerform() 函数 −

<button type="button" onclick="LoopPerform()">TIMER</button>

LoopPerform() 函数内部执行 for、while 和 do-while 循环。总共创建了三个计时器,标签分别为"for-loop"、"while-loop"和"do-while loop",用于衡量这三个循环的性能。

console.time() 方法启动计时器,并接受一个可选的标签参数,用于计算其中代码执行所用的时间。正在执行的代码保存在 console.time() 和 console.timeEnd() 方法中。代码完成执行所用的时间将显示在控制台窗口中 −

function LoopPerform(){
   console.time("for-loop");
   for (; i < 100000; i++){}
      console.timeEnd("for-loop");
   console.time("while-loop");
   while(j<100000)
      j++;
   console.timeEnd("while-loop");
   console.time("do-while loop");
   do{k++;}
   while(k<100000);
   console.timeEnd("do-while loop");
}

相关文章


有用资源