Can I get the output from console.timeEnd() in JS Console? [duplicate] - javascript

I'd like to be able to get the string returned from console.timeEnd('t') in my Google Chrome Javascript Console.
In this example below, I'd like one variable which would contain "t: 0.276ms"
> console.time('t'); console.timeEnd('t');
t: 0.276ms
< undefined
Is this something doable?

In Google Chrome 23.0.1262.2 (Official Build 155904) dev, it looks like it's impossible. The only way I found to be able to calculate time with accuracy is to use window.performance.webkitNow()
Here's a simple example:
var start = window.performance.now();
...
var end = window.performance.now();
var time = end - start;
Read more at http://updates.html5rocks.com/2012/08/When-milliseconds-are-not-enough-performance-now

simply you can use
var begin=Date.now();
something here ...;
var end= Date.now();
var timeSpent=(end-begin)/1000+"secs";
this is the simplest way and it will work on any browser not in only chrome

Small helper to do some time measuring. timerEnd returns the time in ms, also the timers object contains information about how many times the timer with this name was used, the sum of all measured times and the average of the measurements. I find this quite useful, since the measured time for an operation depends on many factors, so it's best to measure it several times and look at the average.
var timers = {};
function timer(name) {
timers[name + '_start'] = window.performance.now();
}
function timerEnd(name) {
if (!timers[name + '_start']) return undefined;
var time = window.performance.now() - timers[name + '_start'];
var amount = timers[name + '_amount'] = timers[name + '_amount'] ? timers[name + '_amount'] + 1 : 1;
var sum = timers[name + '_sum'] = timers[name + '_sum'] ? timers[name + '_sum'] + time : time;
timers[name + '_avg'] = sum / amount;
delete timers[name + '_start'];
return time;
}

console.timeEnd() function puts the time to console, and returns the value
so you can save it to variable
var c = console.timeEnd('a');
c/1000+'s';
or you can save this variable to window object for latest usage
window.c = console.timeEnd('b');
window.c

Related

SoundCloud player from stream unable to get duration

I am currently trying to make a progress bar for my own custom player. For some reason, getDuration() is returning a value whether it is treated like the widget's getDuration with a callback function or as if it just pulling a value.
(duration is declared globally which after testing doesn't seem to make a difference in the problem)
duration = player.getDuration();
var minutes = (duration / 1000) / 60;
var strMin = "" + Math.floor(minutes);
var strSec = "" + Math.floor((minutes - Math.floor(minutes)) * 60);
var pad = "00";
var text = strMin + ":" + pad.substring(0, pad.length - strSec.length) + strSec;
$('#bufferText').html(text);
This is how the API says it would be handled based on description and it is how the other methods from the class work but passing in a callback function also does not work.
For anyone that isn't thinking straight like I was, the player doesn't pull any of the information until buffering/playback starts. Putting the code excerpt inside of a listener for the play-start event of the player fixed the issue.

Js prototype.forEach vs. Array.prototype.forEach.call vs. for

I came across some discussion on a stackoverflow post a couple days back (sorry I cannot remember the post) where, someone suggested that forEach has a time penalty in comparison to for loop (i.e., takes more time to run). To test this, I wrote the following code:
function testPrototypeUse(){
/*
* Checks whether there is a performance penalty in
* invoking prototype methods from builtin objects
* specifically, forEach from Array.prototype
*/
'use strict';
const max_size = 3600000;
let blob = [];
let txt = '';
for(let i=0; i<max_size; i++){
blob.push(i);
}
console.log(''+ max_size +' checks for \'for\' and forEach');
console.log('Initial blob size test: ' + blob.length);
let start = process.hrtime();
Array.prototype.forEach.call(blob, function(n){
txt += n;
});
let elapsed = process.hrtime(start);
console.log('Array.prototype.forEach.call took: Total: '+ (elapsed[0]) +' s, ' + parseFloat(elapsed[1]/10e6).toPrecision(4) +' ms ');
// delete txt; throws Syntax Error: cannot delete unqualified identifier
txt = '';
console.log('Blob size test before for: ' + blob.length);
start = process.hrtime();
for(let i=0; i<blob.length; i++){
txt += i;
}
elapsed = process.hrtime(start);
console.log('For loop took: Total: '+ (elapsed[0]) +' s, ' + parseFloat(elapsed[1]/10e6).toPrecision(4) +' ms ');
txt = '';
console.log('Blob size test before blob.forEach: ' + blob.length);
start = process.hrtime();
blob.forEach(function(i){ txt+=i; });
elapsed = process.hrtime(start);
console.log('blob.forEach took: Total: '+ (elapsed[0]) +' s, ' + parseFloat(elapsed[1]/10e6).toPrecision(4) +' ms ');
}
My initial thought before running the tests were as follows:
There will not be any significant performance penalty.
Array.prototype.forEach.call and blob.forEach would be slightly slower (if at all) than for. My understanding on this being that the creating a function stack and, looking up the prototype chain will add some extra overhead.
After running the test with values between 1000000 - 3600000, the results I got were:
Now, seeing the first 2 results were as I expected (although, the performance penalty was more than I expected for prototype.forEach than for). In case of blob.forEach the penalty was even higher (if I am right, because the compiler had to follow the entire prototype chain to the 2nd last, Array). I was wondering if, there was a any available optimization that can be employed to improve the performance of Array.prototype.forEach.call? I have been using them instead of for loop in my code and, seeing the difference, am worried about penalty when the code has to run under high stress environment.
Thanks a lot in advance.

How to write arguments in function?

I have been using functions but I am not able to tackle this.
What I have done is created a function, then made this to use the values provided by the document class or ids and do the work. Once work is done then just give the data back! It worked!
Now I want to make this function happen for two divs, the first function works good. The issue is with the second one. The function is correct, their is some other bug while writing the result.
Here is my code:
function time_untilCom(id) {
var Time2 = Date.parse(document.getElementById("time_" + 2).value);
var curTime2 = new Date();
var timeToWrite2 = "";
var seconds2 = Math.floor((curTime2 - Time2) / (1000));
if (seconds2 > 0 && seconds2 < 60) {// seconds..
timeToWrite2 = seconds2 + " seconds ago";
$('#update_' + 2).html(seconds2);
$('#jstime_' + 2).html(timeToWrite2 + " <b>Time that was captured!</b>");
}
}
If I use it as it is, it works! The issue comes when I try to replace these
("time_" + 2), ("#update_" + 2), ("#jstime" + 2) with ("time_" + id), ("#update_" + id), ("#jstime_" + id).
What i want to happen is that the function would be provided with a common ID that is applied throughout the div and use that ID, to get the value of time, convert it to seconds, do other stuff and then provide me with the result in the corresponding element with the id that was in the argument.
function works great, it do provide me with the result. But the issue is with the id its not being sent I guess. Or if is being sent then not being applied. What might be the issue here? And don't mind the seconds i have that covered too.
I am really very sorry for short code:
Pardon me, I was about to write the code for the function too. But electricity ran out!
Here is the code: onload="time_untilCom('2'), this is the way I am executing this.
And once in the main code, it will be executed like this: onload="time_untilCom(#row.Id) because I am using ASP.NET Web Pages I will be using the server side code to write the ID from Database. And will then user the ID throughtout the div to update the time!
From what I understand, you probably want to replace the second line
var Time2 = Date.parse(document.getElementById("time_" + 2).value);
with
var Time2 = Date.parse(document.getElementById(id).value);
And at the end you can also use
$('#'+id).html(timeToWrite2 + " <b>Time that was captured!</b>");
You are passing "id" as an argument, but you never use it inside the function. My question is: In your example you are using 2 as appendix to id attributes. Is it the 2 (or other numbers respectively) that you want to have as the id parameter of the function?
Then you could just replace each + 2 in your code by + id
function time_untilCom(id) {
var Time2 = Date.parse(document.getElementById("time_" + id).value);
var curTime2 = new Date();
var timeToWrite2 = "";
var seconds2 = Math.floor((curTime2 - Time2) / (1000));
if (seconds2 > 0 && seconds2 < 60) {// seconds..
timeToWrite2 = seconds2 + " seconds ago";
$('#update_' + id).html(seconds2);
$('#jstime_' + id).html(timeToWrite2 + " <b>Time that was captured!</b>");
}
}
EDIT: Please tell us where and how exactly do you call time_untilCom? Did you pass the id there?

Addition not working in Javascript

I'm really new to Javascript and trying to create a form where I'm running into some trouble...
When I use + it does not add up to the value, instead it just puts it back to back. Ex: 5+10 (510)
Here's my code if you want to take a look at it. I'd appreciate any help since I can't figure this out on my own.
var service = document.getElementById("service");
var serviceprice = service.options[service.selectedIndex].id;
var tech = document.getElementById("tech");
var techprice = tech.options[tech.selectedIndex].id;
var hours = document.getElementById("hours").value;
// The error happens here
var total = techprice * hours + serviceprice;
I also have an html part which the script gets the data from.
That happens whenever you have a string rather than a number. The + operator performs concatenation for strings. Make sure you parse your strings to numbers using parseFloat or parseInt:
var service = document.getElementById("service");
var serviceprice = parseInt(service.options[service.selectedIndex].id, 10);
var tech = document.getElementById("tech");
var techprice = parseInt(tech.options[tech.selectedIndex].id, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
Note that parseInt takes an argument to specify the base. You almost always want base 10.
Try changing this line:
var total = techprice * hours + serviceprice;
to
var total = techprice * hours + parseFloat(serviceprice);
I suspect 'servicePrice' is a string, and it will then try to concatenate the first value (let's say: 100) with the second value (which is, not a number, but a string, let's say 'test'), the result being '100test'.
Try to convert the string to int first with parseInt or to float with parseFloat
This is not especially elegant, but I find it simple, easy, and useful:
var total = -(-techprice * hours - serviceprice);
or even:
var total = techprice * hours -(-serviceprice);
They both eliminate the ambiguous + operator.

How to find the size of localStorage

I am currently developing a site that will make use of HTML5's localStorage. I've read all about the size limitations for different browsers. However, I haven't seen anything on how to find out the current size of a localStorage instance. This question seems to indicate that JavaScript doesn't have a built in way of showing the size for a given variable. Does localStorage have a memory size property that I haven't seen? Is there an easy way to do this that I'm missing?
My site is meant to allow users to enter information in an 'offline' mode, so being able to give them a warning when the storage is almost full is very important.
Execute this snippet in JavaScript console (one line version):
var _lsTotal=0,_xLen,_x;for(_x in localStorage){ if(!localStorage.hasOwnProperty(_x)){continue;} _xLen= ((localStorage[_x].length + _x.length)* 2);_lsTotal+=_xLen; console.log(_x.substr(0,50)+" = "+ (_xLen/1024).toFixed(2)+" KB")};console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");
The same code in multiple lines for reading sake
var _lsTotal = 0,
_xLen, _x;
for (_x in localStorage) {
if (!localStorage.hasOwnProperty(_x)) {
continue;
}
_xLen = ((localStorage[_x].length + _x.length) * 2);
_lsTotal += _xLen;
console.log(_x.substr(0, 50) + " = " + (_xLen / 1024).toFixed(2) + " KB")
};
console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");
or add this text in the field 'location' of a bookmark for convenient usage
javascript: var x, xLen, log=[],total=0;for (x in localStorage){if(!localStorage.hasOwnProperty(x)){continue;} xLen = ((localStorage[x].length * 2 + x.length * 2)/1024); log.push(x.substr(0,30) + " = " + xLen.toFixed(2) + " KB"); total+= xLen}; if (total > 1024){log.unshift("Total = " + (total/1024).toFixed(2)+ " MB");}else{log.unshift("Total = " + total.toFixed(2)+ " KB");}; alert(log.join("\n"));
P.S. Snippets are updated according to request in the comment. Now the calculation includes the length of the key itself.
Each length is multiplied by 2 because the char in javascript stores as UTF-16 (occupies 2 bytes)
P.P.S. Should work both in Chrome and Firefox.
Going off of what #Shourav said above, I wrote a small function that should accurately grab all your the localStorage keys (for the current domain) and calculate the combined size so that you know exactly how much memory is taken up by your localStorage object:
var localStorageSpace = function(){
var allStrings = '';
for(var key in window.localStorage){
if(window.localStorage.hasOwnProperty(key)){
allStrings += window.localStorage[key];
}
}
return allStrings ? 3 + ((allStrings.length*16)/(8*1024)) + ' KB' : 'Empty (0 KB)';
};
Mine returned: "30.896484375 KB"
You can get the current size of the local storage data using the Blob function. This may not work in old browsers, check the support for new Blob and Object.values() at caniuse.
Example:
return new Blob(Object.values(localStorage)).size;
Object.values() turns the localStorage object to an array. Blob turns the array into raw data.
IE has a remainingSpace property of the Storage object. The other browsers have no equivalent at this time.
I believe that the default amount of space is 5MB, although I have not tested it personally.
Here is a simple example of how to do this and should work with every browser
alert(1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length);
Hope this help someone.
Because Jas- example on jsfiddle does not work for me I came up with this solution.
(thanks to Serge Seletskyy and Shourav for their bits I used in the code below)
Below is the function that can be used to test how much space is available for localStorage and (if any keys are already in lS) how much space is left.
It is a little brute force but it works in almost every browser... apart from Firefox.
Well in desktop FF it takes ages (4-5min) to complete, and on Android it just crashes.
Underneath the function is a short summary of tests that I have done in different browsers on different platforms. Enjoy!
function testLocalStorage() {
var timeStart = Date.now();
var timeEnd, countKey, countValue, amountLeft, itemLength;
var occupied = leftCount = 3; //Shurav's comment on initial overhead
//create localStorage entries until localStorage is totally filled and browser issues a warning.
var i = 0;
while (!error) {
try {
//length of the 'value' was picked to be a compromise between speed and accuracy,
// the longer the 'value' the quicker script and result less accurate. This one is around 2Kb
localStorage.setItem('testKey' + i, '11111111112222222222333333333344444444445555555555666661111111111222222222233333333334444444444555555555566666');
} catch (e) {
var error = e;
}
i++;
}
//if the warning was issued - localStorage is full.
if (error) {
//iterate through all keys and values to count their length
for (var i = 0; i < localStorage.length; i++) {
countKey = localStorage.key(i);
countValue = localStorage.getItem(localStorage.key(i));
itemLength = countKey.length + countValue.length;
//if the key is one of our 'test' keys count it separately
if (countKey.indexOf("testKey") !== -1) {
leftCount = leftCount + itemLength;
}
//count all keys and their values
occupied = occupied + itemLength;
}
;
//all keys + values lenght recalculated to Mb
occupied = (((occupied * 16) / (8 * 1024)) / 1024).toFixed(2);
//if there are any other keys then our 'testKeys' it will show how much localStorage is left
amountLeft = occupied - (((leftCount * 16) / (8 * 1024)) / 1024).toFixed(2);
//iterate through all localStorage keys and remove 'testKeys'
Object.keys(localStorage).forEach(function(key) {
if (key.indexOf("testKey") !== -1) {
localStorage.removeItem(key);
}
});
}
//calculate execution time
var timeEnd = Date.now();
var time = timeEnd - timeStart;
//create message
var message = 'Finished in: ' + time + 'ms \n total localStorage: ' + occupied + 'Mb \n localStorage left: ' + amountLeft + "Mb";
//put the message on the screen
document.getElementById('scene').innerText = message; //this works with Chrome,Safari, Opera, IE
//document.getElementById('scene').textContent = message; //Required for Firefox to show messages
}
And as promised above some test in different browsers:
GalaxyTab 10.1
Maxthon Pad 1.7 ~1130ms 5Mb
Firefox 20.0(Beta 20.0) crashed both
Chrome 25.0.1364.169 ~22250ms /5Mb
Native (identifies as Safari 4.0/Webkit534.30) ~995ms /5Mb
iPhone 4s iOS 6.1.3
Safari ~ 520ms /5Mb
As HomeApp ~525ms / 5Mb
iCab ~ 710ms /5mb
MacBook Pro OSX 1.8.3 (Core 2 Duo 2.66 8Gb memory)
Safari 6.0.3 ~105ms /5Mb
Chrome 26.0.1410.43 ~3400ms /5Mb
Firefox 20.0 300150ms(!) /10Mb (after complaining about script running to long)
iPad 3 iOS 6.1.3
Safari ~430ms /5Mb
iCab ~595ms /5mb
Windows 7 -64b (Core 2 Duo 2.93 6Gb memory)
Safari 5.1.7 ~80ms /5Mb
Chrome 26.0.1410.43 ~1220ms /5Mb
Firefox 20.0 228500ms(!) /10Mb (after complaining about script running to long)
IE9 ~17900ms /9.54Mb ( if any console.logs are in the code does not work until DevTools are opened)
Opera 12.15 ~4212ms /3.55Mb (this is when 5Mb is selected, but Opera asks nicely if we want increase the amount of lS, unfortunately it crashes if test conducted a few times in a row)
Win 8 (Under Parallels 8)
IE10 ~7850ms /9.54Mb
You can calculate your localstorage by following methods:
function sizeofAllStorage(){ // provide the size in bytes of the data currently stored
var size = 0;
for (i=0; i<=localStorage.length-1; i++)
{
key = localStorage.key(i);
size += lengthInUtf8Bytes(localStorage.getItem(key));
}
return size;
}
function lengthInUtf8Bytes(str) {
// Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
var m = encodeURIComponent(str).match(/%[89ABab]/g);
return str.length + (m ? m.length : 0);
}
console.log(sizeofAllStorage());
Finally size in bytes will be logged in browser.
I would use the code of #tennisgen which get all and count the content, but I count the keys themselves:
var localStorageSpace = function(){
var allStrings = '';
for(var key in window.localStorage){
allStrings += key;
if(window.localStorage.hasOwnProperty(key)){
allStrings += window.localStorage[key];
}
}
return allStrings ? 3 + ((allStrings.length*16)/(8*1024)) + ' KB' : 'Empty (0 KB)';
};
The way I went about this problem is to create functions for finding out the used space and remaining space in Local Storage and then a function that calls those functions to determine the max storage space.
function getUsedSpaceOfLocalStorageInBytes() {
// Returns the total number of used space (in Bytes) of the Local Storage
var b = 0;
for (var key in window.localStorage) {
if (window.localStorage.hasOwnProperty(key)) {
b += key.length + localStorage.getItem(key).length;
}
}
return b;
}
function getUnusedSpaceOfLocalStorageInBytes() {
var maxByteSize = 10485760; // 10MB
var minByteSize = 0;
var tryByteSize = 0;
var testQuotaKey = 'testQuota';
var timeout = 20000;
var startTime = new Date().getTime();
var unusedSpace = 0;
do {
runtime = new Date().getTime() - startTime;
try {
tryByteSize = Math.floor((maxByteSize + minByteSize) / 2);
//localStorage.setItem(testQuotaKey, new Array(tryByteSize).join('1'));
//Recommended by #pkExec and #jrob007
localStorage.setItem(testQuotaKey, String('1').repeat(tryByteSize));
minByteSize = tryByteSize;
} catch (e) {
maxByteSize = tryByteSize - 1;
}
} while ((maxByteSize - minByteSize > 1) && runtime < timeout);
localStorage.removeItem(testQuotaKey);
if (runtime >= timeout) {
console.log("Unused space calculation may be off due to timeout.");
}
// Compensate for the byte size of the key that was used, then subtract 1 byte because the last value of the tryByteSize threw the exception
unusedSpace = tryByteSize + testQuotaKey.length - 1;
return unusedSpace;
}
function getLocalStorageQuotaInBytes() {
// Returns the total Bytes of Local Storage Space that the browser supports
var unused = getUnusedSpaceOfLocalStorageInBytes();
var used = getUsedSpaceOfLocalStorageInBytes();
var quota = unused + used;
return quota;
}
In addition to #serge's answer which is most voted here, size of the keys need to be considered. Code below will add the size of the keys stored in localStorage
var t = 0;
for (var x in localStorage) {
t += (x.length + localStorage[x].length) * 2;
}
console.log((t / 1024) + " KB");
As the spec goes, each character of a string is 16 bit.
But inspecting with chrome (Settings>Content Settings>Cookies & Site data) shows us that initiating localStorage takes 3kB (overhead size)
And stored data size follows this relation (accurate to 1kB)
3 + ((localStorage.x.length*16)/(8*1024)) kB
where localStorage.x is your storage string.
Yes, this question was asked like 10 years ago. But for those interested (like myself, as I am building an offline text editor that saves data with local storage) and suck at programming, you could use something simple like this:
var warning = 1;
var limit = 2000000; //2 million characters, not really taking in account to bytes but for tested number of characters stored
setInterval(function() {
localStorage["text"] = document.getElementById("editor").innerHTML; //gets text and saves it in local storage under "text"
if(localStorage["text"].length > limit && warning == 1){
alert("Local Storage capacity has been filled");
warning = 2; //prevent a stream of alerts
}
}, 1000);
//setInterval function saves and checks local storage
The best way to get the amount of storage filled is to view the site settings (say, if you stored an image in local storage). At least in chrome, you can see the amount of bytes used (ie: 1222 bytes). However, the best ways to see filled local storage with js have already been mentioned above, so use them.
//Memory occupy by both key and value so Updated Code.
var jsonarr=[];
var jobj=null;
for(x in sessionStorage) // Iterate through each session key
{
jobj={};
jobj[x]=sessionStorage.getItem(x); //because key will also occupy some memory
jsonarr.push(jobj);
jobj=null;
}
//https://developer.mozilla.org/en/docs/Web/JavaScript/Data_structures
//JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values.
var size=JSON.stringify(jsonarr).length*2; //16-bit that's why multiply by 2
var arr=["bytes","KB","MB","GB","TB"]; // Define Units
var sizeUnit=0;
while(size>1024){ // To get result in Proper Unit
sizeUnit++;
size/=1024;
}
alert(size.toFixed(2)+" "+arr[sizeUnit]);
window.localStorage.remainingSpace

Categories

Resources