Home > Web Front-end > JS Tutorial > body text

JavaScript中的console.time()函数详细介绍_javascript技巧

WBOY
Release: 2016-05-16 16:23:49
Original
1356 people have browsed it

如果需要在Web调试过程中知道代码执行的时间,那么可以通过在JavaScript代码中添加console.time()语句和console.timeEnd()语句来对程序的执行进行计时。以下面这个耗时较长的foo()函数为例:


复制代码 代码如下:

function foo(){
    var x = 4.237;
    var y = 0;
    for (var i=0; i         y = y + x*x;
    }
    return y;
}


如果需要知道函数执行过程中消耗了多长时间,可以在foo()函数调用之前插入console.time()语句,在其调用结束后插入console.timeEnd()语句:


复制代码 代码如下:

console.time("test");
foo();
console.timeEnd("test");


程序执行完毕后,控制台会显示此次计时的结果:”test: 1797ms”,显示的日志级别为info。

console.time()和console.timeEnd()接受一个字符串作为参数,该字符串相当于计时的id。浏览器会将拥有相同参数(id)的console.time()与console.timeEnd()进行配对,记录两者之间的时间差。因此,可以通过使用不同的id来对JavaScript程序中不同的地方进行计时。

浏览器支持

对于各个浏览器,console.time()计时的支持情况如下:

Firefox。10.0后原生支持。对于之前版本的Firefox,可以通过安装Firebug插件来实现。详见:https://developer.mozilla.org/en-US/docs/Web/API/console.time?redirectlocale=en-US&redirectslug=DOM%2Fconsole.time
Google Chrome。2.0后原生支持。详见:https://developers.google.com/chrome-developer-tools/docs/console-api#consoletimelabel
IE。IE11中原生支持。对于之前版本的IE,可以通过安装Firebug Lite来实现。详见:http://msdn.microsoft.com/en-us/library/ie/dn265071%28v=vs.85%29.aspx
Safari。4.0后原生支持。详见:https://developer.apple.com/library/safari/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html
Opera。支持。详见:http://www.opera.com/dragonfly/documentation/console/

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!