How can I find out how much time elapses between two events using javascript? for example, to a millisecond?
This is surprisingly hard to do.
var start = new Date(); // Do things here var finish = new Date(); var difference = new Date(); difference.setTime(finish.getTime() - start.getTime()); alert( difference.getMilliseconds() );
When performing arithmetic operations on objects, Datethey are implicitly converted to milliseconds (from 1970-01-01 00:00:00 UTC), so all you need to do is subtract Datecreated when the operation starts with Datecreated when the operation was completed.
Date
var start = new Date(); doSomeHeavyWork(); var end = new Date(); var millisecondsElapsed = end - start;
.
console.time("timer name") console.timeEnd("timer name")
, firebug ( firefox), . : javascript
?
:
// event 1 document.getElementById('elId').onclick = function () { timer.start('myTimer1'); }; // event 2 document.getElementById('otherElement').onclick = function () { alert(timer.stop('myTimer1')); // alerts the time difference in ms };
Implementation:
var timer = (function () { var startTimes = {}; // multiple start times will be stored here return { start: function (id) { id = id || 'default'; // set id = 'default' if no valid argument passed startTimes[id] = +new Date; // store the current time using the timer id }, stop: function (id) { id = id || 'default'; var diff = (+new Date - startTimes[id]); // get the difference delete startTimes[id]; // remove the stored start time return diff || undefined; // return the difference in milliseconds } }; }());
var initialTime = (new Date).getTime(), i = 55000; (function() { while ( i-- ) { setTimeout( function(){}, 20 ); } })() var finalTime = ( new Date ).getTime(), diff = (new Date); diff.setTime( finalTime - initialTime ); alert( diff.getMilliseconds() + 'ms' )
Source: https://habr.com/ru/post/1718619/More articles:remove item from priority queue in C ++ stl - c ++how to use yum private repository on amazon-s3 to provide amazon-ec2 instances? - httpshow to defer a default action? - jqueryMultiple threads for multiple ports? - c ++Creating tables with pylons and SQLAlchemy - pythonПочему мой Perl-печать показывает HASH (0x100a2d018)? - stringEJB 3 with JDBC - jdbcC # - Locking a resource when retrieving from a dictionary - dictionaryflex newbie: you can create MXML on the fly - flexMaven2 package with Flex4 installation - flexAll Articles