Skip to content

Instantly share code, notes, and snippets.

@egorvinogradov
Last active August 10, 2023 18:42
Show Gist options
  • Save egorvinogradov/4493378 to your computer and use it in GitHub Desktop.
Save egorvinogradov/4493378 to your computer and use it in GitHub Desktop.
Cross-browser console.time, console.timeCapture & console.timeEnd implementation.
if ( console && console.log ) {
console._timeStamps = {};
console.time = function(name){
console._timeStamps[name] = new Date();
console.log(name + ': ' + console._timeStamps[name]);
};
console.timeCapture = function(name){
if ( console._timeStamps[name] ) {
var timeStamp = +new Date() - +console._timeStamps[name];
var seconds = Math.floor(timeStamp / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var timeStr = name + ':';
if ( hours >= 1 ) {
timeStr += ' ' + hours + 'h';
}
if ( minutes >= 1 ) {
timeStr += ' ' + minutes + 'm';
}
if ( seconds >= 1 ) {
timeStr += ' ' + seconds + 's';
}
if ( timeStamp >= 1 ) {
timeStr += ' ' + timeStamp % 1000 + 'ms';
}
console.log(timeStr);
return;
}
console.log(name + ' is not found');
};
console.timeEnd = function(name){
console.timeCapture(name);
delete console._timeStamps[name];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment