I need a function that will print letters one by one but make pauses after ",".
I tried to do it like this but it didn't work :
var span = document.getElementById('text')
function print(string){
var i = 0
var time = 50
var timer = setInterval(function(){
span.innerHTML += string[i++]
if(string[i] == ","){
time = 150
}else{
time = 50
}
},time)
}
I am not sure you can change the time of setTimeinterval once defined. It is better to use a setTimeout. I'm using recursive function to achieve the desired -
function print(string, i){
var time = 50
if(string[i]==",") time = 1000
setTimeout(function(){
span.innerHTML += string[i]
if(i<string.length-1) print(string,++i)
},time)
}
complete example can be found here
First, I don't think setInterval is what you're looking for. Since it seems you just want to print each character with a delay, setTimeout would work best in this situation.
I would break this up so that you can focus on printing a single character at a time, and then you can call that in your main print function for each character in the string.
This is how I would do something like this, using Promises:
const printCharacter = (ch, idx) => new Promise(resolve => {
let time = 50 * idx;
if(ch === ',') {
time = 150 + time * idx;
}
setTimeout(() => {
const span = document.getElementById('text');
span.innerHTML += ch;
resolve();
}, time)
});
const print = async string => {
for(let i = 0; i < string.length; i++) {
await printCharacter(string[i], i);
}
};
There are some bugs that could present itself here, such as the timing for multiple commas present in your base string. This is just my first iteration.
Instead of using an interval, I recommend using a for loop to iterate the string and a Promise to pause as long as desired.
Side note, use textContent instead of innerHTML. The former is like myCar.cangeTires(); myCar.closeDoors(), the latter is like myCar.do('change tires'); myCar.do('close doors');.
let sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
var span = document.getElementById('text');
let print = async string => {
span.textContent = '';
for (let c of string) {
span.textContent += c;
await sleep(c === ',' ? 500 : 50);
}
};
print('my text, and a comma');
<span id="text"></span>
Related
I've been bashing my head against this wall I am completely new to JavaScript coming from c#
and I am completely baffled for my class I have to smooth out a simple code we made to count down from zero by making it into a loop and for the life of me I just cant get it to work
var i = 10;
var timeout = 10000;
var x = 10
if (i == 5) {
alert("help me")
}
while (i > 0) {
//10
setTimeout(() => {
document.getElementById("counter").innerHTML = i;
i = i - 1;
}, timeout);
timeout = timeout - 1000;
}
Asynchrony in JavaScript is a rather involved subject.
Traditional loops (for, while, do..while, for..of) are synchronous, and so cannot help you reach your goal here.
To do what you want, you can use indirect recursion like so:
const countdown = (from = 10, to = 0, interval = 1000, cb = console.log) => {
if(from < 0) return
cb(from)
setTimeout(() =>
countdown(--from), interval)
}
countdown()
There is also a more modern approach that enables the use of syntax that looks a bit more familiar. This approach uses for await... of, the syntax for which does not appear to be supported by StackOverflow's transpiler:
const delay = (interval) => new Promise((resolve) =>
setTimeout(resolve, interval))
async function* countdown(from = 10, to = 0, interval = 1000) {
for(;from >= 0; from--) {
yield from
await delay(interval)
}
}
for await(let count of countdown()) {
console.log(count)
}
setInterval is what you're looking for to execute a function every certain amount of time:
let i = 10;
let interval = setInterval(function() {
document.getElementById("counter").innerHTML = i;
i--;
if(i < 0) clearInterval(interval);//Clear the interval when complete
}, 1000);//Every 1000 ms = every second
The code below will countdown to zero.
var i = 10;
while (i > 0){
i--;
console.log(i);
}
Okay, so I have created this javascript text-animation that has a delay when writing text to
my p element "output". The animation works just fine...but I decided that I wanted to add text color to specific words in my "message" parameter. I made that happen by using this code:
function write(message,clear,delay) {
if(clear == true) clearMessage();
if(typeof delay != "number") delay = game.message.delay;
let q = undefined;
let output = document.getElementById("output");
let applyingColor = false;
let dest = output;
for(var i = 0 ; i < message.length ; i++) {
let cur = i;
let letter = message.charAt(i);
let wait = delay*i;
q = setTimeout(() => {
if(letter == "<") {
letter = "";
applyingColor = true;
let color = undefined;
let a = message.substring(cur+1,message.length);
let colorSig = a.substring(0,a.indexOf("/"));
color = colorSig;
let span = document.createElement("span");
span.style.color = color;
output.appendChild(span);
dest = span;
} else if(letter == ">") {
letter = "";
dest = output;
} else if(letter == "|") {
letter = "<br>";
}
if(applyingColor) {
if(letter != "/") {
return;
} else {
applyingColor = false;
return;
}
}
dest.innerHTML += letter;
},wait);
writingQueue.push(q);
}
}
the code above delays each character while also checking for very specific text such as
<rgb(255,0,0)/ this is red>. the "<" and the ">" are starting and ending signifiers for the colored text, while the "/" is used to mark where the end of the color goes. The text you want to be colored would go before ">" and after "/". and that makes it red! or any color you want. But I noticed a small detail. Whenever you use this, it creates an additional delay. For example if you did something like...
write("Hello, foo! My name is <red/ bar>!");
it would delay the "b" in "bar" longer than it would delay the "f" in "foo".
I think the problem is being caused by
if(applyingColor) {
if(letter != "/") {
return
} else {
applyingColor = false
return
}
}
at around the bottom body of the q = setTimeout(...).
What this code above does is skip over any letters that are not "/" while applyingColor is true, then turns it to false when it eventually reaches that wonderful little marker ("/") and returns one last time.
Honestly I dont know how to fix this. I've been working on this for hours now and my head hurts a lot. I could really use some help!
Oh! I forgot to mention. You can just ignore the "clear" and "delay" parameters. I do not believe they are relevant to my issue. The delay parameter is just the delay between each character. I have it to where it has a default value right now. And clear is just to clear previous text and clear out the writingQueue variable.
The problem in your current code is that as i increases over every iteration, so wait is being recalculated every check.. The first time it's 0 * delay, the second 1 * delay, the third 2 * delay. The solution while implementing only the current code would be to just define wait outside of the for loop.
buggy
let delay = 3;
for(var i = 0 ; i < 93 ; i++) {
let wait = delay * i;
}
let delay = 3;
let wait = 3 * 3;
for(var i = 0 ; i < 93 ; i++) {
}
good
However, there is an even better way to do javascript animations like the one you made, assuming you want them all to take the same amount of time (given your problem, as I understand it, is that the later letters are taking longer <?>) & you're making a webpage
window.requestAnimationFrame(function)
which will wait until the next frame to execute the code, making it always happen with the illusion of no delay to the user
suboptimal
q = setTimeout(() => if(letter == "<") {
/*...*/
faster, very rarely skips frames
q = window.requestAnimationFrame(() => if(letter == "<") {
/*...*/
if you want the letters to change all at once, you can just put the entire
for loop in a function and then call it using window.requestAnimationFrame(function).
window.requestAnimationFrame(colorIn);
function colorIn() {
for(var i = 0 ; i < message.length ; i++) {
let letter = message.charAt(i);
if(letter == "<") {
/*...*/
which will either make the letters changed all at once. if it can't, they'll change after dropping a few frames- though that should only happen if your computer has a virus or you change the color of an absolutely massive string
I'm trying to print one letter after another but this code just waits 100ms and then prints the value with no pauses. Any idea why this happens and how to fix it?
Code:
for (let i = 0; i < welcText.length; i++) {
setTimeout(()=>{
welcome.innerText += welcText[i];
},100);
}
Note that setTimeout does not actually delay the running of the code that comes after; it just schedules for something to happen in the future. So all the letters are added at the same time, after 100 milliseconds.
The most straightforward way to fix it is to make each subsequent timeout wait a bit longer, by multiplying the delay with the index of the letter (i * 100):
const welcome = document.getElementById('welcome');
const welcText = 'Welcome!';
for (let i = 0; i < welcText.length; i++) {
setTimeout(() => {
welcome.innerText += welcText[i];
}, i * 100);
}
<div id="welcome"></div>
The following function divtxt() returns a Promise. You can use it to send a txt to a div with a given id and let each letter appear in ms intervals. AND: you can build a chain of any number of follow-up actions with it:
function divtxt(id, txt, ms, wait = 0) {
const div = document.getElementById(id);
return new Promise((res, rej) => {
setTimeout(() => { // optional initial timeout, when wait>0
div.textContent = "";
const a = txt.split(""),
iv = setInterval(() => {
if (a.length)
div.textContent += a.shift();
else {
clearInterval(iv);
res(txt);
}
}, ms);
}, wait);
});
}
divtxt("welcome", "Hello world, this is my way of doing it! 🤩", 100)
.then(prevText => (console.log(prevText + ' is done.'),
divtxt("descr", "You can also chain this function with any number of consecutive actions."
+" Now: wait for 2 seconds ...", 100)))
.then(() => divtxt("welcome", "This promised-based approach REALLY lets you do it!! 👍🏻", 50, 2000))
.then(() => (console.log("ready?"),"Yes! I am REALLY DONE now! 😁"))
.then(console.log)
#welcome {
font-weight: 900
}
<div id="welcome"></div>
<div id="descr"></div>
You can do it using setInterval instead, and using an iterator to call the next char of the string every time. This is a bit more complicated, but has the advantage of not having multiple schedulers running if the string is too long. See the working example below.
const welcome = document.getElementById('welcome');
const welcomeText = 'Welcome!';
// returns a function that returns the next char in the string everytime its called
function createIterator(string) {
let currentIndex = 0;
return function() {
return string[currentIndex++];
}
}
// initializes the iterator with the text
let welcomeIterator = createIterator(welcomeText);
let welcomeInterval = setInterval(function() {
let nextChar = welcomeIterator();
// if we finish the string we clear the interval
if (!nextChar) {
return clearInterval(welcomeInterval);
}
// if the char exists, we append it to the div
welcome.innerText += nextChar;
}, 100);
<div id="welcome"></div>
you can do it like this also
const welcText = 'Welcome!';
let i = 0;
const interval = setInterval(() => {
if (i >= welcText.length) {
clearInterval(interval);
} else {
document.getElementById('helloword').innerHTML += welcText[i];
i++;
}
}, 100);
<h1 id="helloword"></h1>
I wrote this code in JS:
function startFunction() {
p1 = document.getElementById('p1').innerHTML;
for (var i=1; i<=p1.length; i++) {
alert(p1.slice(0, i));
}
}
I call the function with onload event in html:
<body onload="startFunction()">
And thi is the paragraph with p1 id:
<p id="p1">Hi, I'm</p>
How can I make a delay for the for loop. I want my program to write the p1 text letter by letter.
You can not and should not delay anything inside a loop, because that is how the nonresponsive pages are made: the browser does not react to user actions or do anything visible until the JavaScript code returns.
Instead, you can use some timer, like setInterval():
function startFunction() {
var p1 = document.getElementById('p1');
var txt = p1.innerHTML;
var i=0;
var timer = setInterval(function() {
p1.innerHTML = txt.slice(0,i++);
if(i>txt.length) {
clearInterval(timer);
}
},500);
}
startFunction();
<p id="p1">Hi, I'm</p>
var alertEachLetter =function(p1, i){
setTimeout(function(){
alert(p1.slice(0, i));
},1000);
};
function startFunction() {
p1 = document.getElementById('p1').innerHTML;
for (var i=1; i<=p1.length; i++) {
alertEachLetter(p1, i);
}
}
why create this alertEachLetter function. for that you need to check this link
setTimeout in for-loop does not print consecutive values
You don't need a loop, you need an interval. Javascript's interval feature will call your function at (approximately) the requested interval. So, for example:
function startFunction() {
var p1 = document.getElementById('p1').innerHTML
var count = 1
var finished = p1.length
var iv = setInterval(function() {
alert(p1.slice(0,count++))
if (count > finished) {
clearInterval(iv) // stops the interval from firing once we finish our task
}
}, 1000) // 1000 ms, or every second.
}
Here's a quick example using setTimeout instead of setInterval. There's not much difference except you don't have to clear the timeout - you simply don't run it if it doesn't meet a condition.
// cache the elements
const p1 = document.getElementById('p1');
const out = document.getElementById('out');
// make the text content from p1 iterable and split it into
// the head (first element), and tail (everything else)
const [head, ...tail] = [...p1.textContent];
const loop = function loop(head, tail) {
// update the output text content with the result of head
out.textContent = head;
// if there's anything left of the tail array
if (tail.length) {
// remove the first element of tail and
// add it to head
head += tail.shift();
// call the function again with the new head and tail
setTimeout(loop, 200, head, tail);
}
// pass in the head and tail to the function
}(head, tail);
#p1 { display: none; }
<p id="p1">Content written letter by letter</p>
<p id="out"></p>
Below is an approach I think may help you achieve what youre trying to do. This approach uses setInterval (instead of a loop) to execute a function multiple times. See the comments to understand the code logic:
//Grab our DOM elements
var p1 = document.getElementById('p1').innerHTML;
var copy = document.getElementById('copy');
//Execute a function every 250 milliseconds
var intervalId = setInterval(onInterval, 250);
//nextLetter is a function that will return the character at a particular index in the string. The function will increase the index each time it is called. The function will return null once it exceeds the innerHTML length. c is a "private" variable that can't be modified elsewhere in the program.
var nextLetter = (function(i, limit) {
var c = i;
return function() {
var idx = c++;
if (idx > limit) {
return null;
}
return p1.charAt(idx);
};
})(0, p1.length);
//The function we will execute at each interval
function onInterval() {
var letter = nextLetter();
if (letter) {
copy.innerHTML += letter;
} else {
console.log('End of content reached - removing interval');
clearTimeout(intervalId);
}
}
<p id="p1">Make sure to read the in-code comments</p>
<p id="copy"></p>
I have a piece of JavaScript code that I am executing using the node.js interpreter.
for(var i = 1; i < LIMIT; i++) {
var user = {
id: i,
name: "MongoUser [" + i + "]"
};
db.users.save(user, function(err, saved) {
if(err || !saved) {
console.log("Error");
} else {
console.log("Saved");
}
});
}
How can I measure the time taken by these database insert operations? I could compute the difference of date values after and before this piece of code but that would be incorrect because of the asynchronous nature of the code.
Use the Node.js console.time() and console.timeEnd():
var i;
console.time("dbsave");
for(i = 1; i < LIMIT; i++){
db.users.save({id : i, name : "MongoUser [" + i + "]"}, end);
}
end = function(err, saved) {
console.log(( err || !saved )?"Error":"Saved");
if(--i === 1){
console.timeEnd("dbsave");
}
};
There is a method that is designed for this. Check out process.hrtime(); .
So, I basically put this at the top of my app.
var start = process.hrtime();
var elapsed_time = function(note){
var precision = 3; // 3 decimal places
var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
console.log(process.hrtime(start)[0] + " s, " + elapsed.toFixed(precision) + " ms - " + note); // print message + time
start = process.hrtime(); // reset the timer
}
Then I use it to see how long functions take. Here's a basic example that prints the contents of a text file called "output.txt":
var debug = true;
http.createServer(function(request, response) {
if(debug) console.log("----------------------------------");
if(debug) elapsed_time("recieved request");
var send_html = function(err, contents) {
if(debug) elapsed_time("start send_html()");
response.writeHead(200, {'Content-Type': 'text/html' } );
response.end(contents);
if(debug) elapsed_time("end send_html()");
}
if(debug) elapsed_time("start readFile()");
fs.readFile('output.txt', send_html);
if(debug) elapsed_time("end readFile()");
}).listen(8080);
Here's a quick test you can run in a terminal (BASH shell):
for i in {1..100}; do echo $i; curl http://localhost:8080/; done
Invoking console.time('label') will record the current time in milliseconds, then later calling console.timeEnd('label') will display the duration from that point.
The time in milliseconds will be automatically printed alongside the label, so you don't have to make a separate call to console.log to print a label:
console.time('test');
//some code
console.timeEnd('test'); //Prints something like that-> test: 11374.004ms
For more information, see Mozilla's developer docs on console.time.
Surprised no one had mentioned yet the new built in libraries:
Available in Node >= 8.5, and should be in Modern Browers
https://developer.mozilla.org/en-US/docs/Web/API/Performance
https://nodejs.org/docs/latest-v8.x/api/perf_hooks.html#
Node 8.5 ~ 9.x (Firefox, Chrome)
// const { performance } = require('perf_hooks'); // enable for node
const delay = time => new Promise(res=>setTimeout(res,time))
async function doSomeLongRunningProcess(){
await delay(1000);
}
performance.mark('A');
(async ()=>{
await doSomeLongRunningProcess();
performance.mark('B');
performance.measure('A to B', 'A', 'B');
const measure = performance.getEntriesByName('A to B')[0];
// firefox appears to only show second precision.
console.log(measure.duration);
// apparently you should clean up...
performance.clearMarks();
performance.clearMeasures();
// Prints the number of milliseconds between Mark 'A' and Mark 'B'
})();
https://repl.it/#CodyGeisler/NodeJsPerformanceHooks
Node 12.x
https://nodejs.org/docs/latest-v12.x/api/perf_hooks.html
const { PerformanceObserver, performance } = require('perf_hooks');
const delay = time => new Promise(res => setTimeout(res, time))
async function doSomeLongRunningProcess() {
await delay(1000);
}
const obs = new PerformanceObserver((items) => {
console.log('PerformanceObserver A to B',items.getEntries()[0].duration);
// apparently you should clean up...
performance.clearMarks();
// performance.clearMeasures(); // Not a function in Node.js 12
});
obs.observe({ entryTypes: ['measure'] });
performance.mark('A');
(async function main(){
try{
await performance.timerify(doSomeLongRunningProcess)();
performance.mark('B');
performance.measure('A to B', 'A', 'B');
}catch(e){
console.log('main() error',e);
}
})();
For anyone want to get time elapsed value instead of console output :
use process.hrtime() as #D.Deriso suggestion, below is my simpler approach :
function functionToBeMeasured() {
var startTime = process.hrtime();
// do some task...
// ......
var elapsedSeconds = parseHrtimeToSeconds(process.hrtime(startTime));
console.log('It takes ' + elapsedSeconds + 'seconds');
}
function parseHrtimeToSeconds(hrtime) {
var seconds = (hrtime[0] + (hrtime[1] / 1e9)).toFixed(3);
return seconds;
}
var start = +new Date();
var counter = 0;
for(var i = 1; i < LIMIT; i++){
++counter;
db.users.save({id : i, name : "MongoUser [" + i + "]"}, function(err, saved) {
if( err || !saved ) console.log("Error");
else console.log("Saved");
if (--counter === 0)
{
var end = +new Date();
console.log("all users saved in " + (end-start) + " milliseconds");
}
});
}
Old question but for a simple API and light-weight solution; you can use perfy which uses high-resolution real time (process.hrtime) internally.
var perfy = require('perfy');
function end(label) {
return function (err, saved) {
console.log(err ? 'Error' : 'Saved');
console.log( perfy.end(label).time ); // <——— result: seconds.milliseconds
};
}
for (var i = 1; i < LIMIT; i++) {
var label = 'db-save-' + i;
perfy.start(label); // <——— start and mark time
db.users.save({ id: i, name: 'MongoUser [' + i + ']' }, end(label));
}
Note that each time perfy.end(label) is called, that instance is auto-destroyed.
Disclosure: Wrote this module, inspired by D.Deriso's answer. Docs here.
You could also try exectimer. It gives you feedback like:
var t = require("exectimer");
var myFunction() {
var tick = new t.tick("myFunction");
tick.start();
// do some processing and end this tick
tick.stop();
}
// Display the results
console.log(t.timers.myFunction.duration()); // total duration of all ticks
console.log(t.timers.myFunction.min()); // minimal tick duration
console.log(t.timers.myFunction.max()); // maximal tick duration
console.log(t.timers.myFunction.mean()); // mean tick duration
console.log(t.timers.myFunction.median()); // median tick duration
[edit] There is an even simpler way now to use exectime. Your code could be wrapped like this:
var t = require('exectimer'),
Tick = t.Tick;
for(var i = 1; i < LIMIT; i++){
Tick.wrap(function saveUsers(done) {
db.users.save({id : i, name : "MongoUser [" + i + "]"}, function(err, saved) {
if( err || !saved ) console.log("Error");
else console.log("Saved");
done();
});
});
}
// Display the results
console.log(t.timers.myFunction.duration()); // total duration of all ticks
console.log(t.timers.saveUsers.min()); // minimal tick duration
console.log(t.timers.saveUsers.max()); // maximal tick duration
console.log(t.timers.saveUsers.mean()); // mean tick duration
console.log(t.timers.saveUsers.median()); // median tick duration
You can use a wrapper function to easily report the execution time of any existing function.
A wrapper is a used to extend an existing function to do something before and after the existing function's execution - and is a convenient way to compose logic.
Here is an example of using the withDurationReporting wrapper:
// without duration reporting
const doSomethingThatMayTakeAWhile = async (someArg: string, anotherArg: number) => {
/** your logic goes here */
}
// with duration reporting
const doSomethingThatMayTakeAWhileWithReporting = withDurationReporting(
'doSomethingThatMayTakeAWhile',
doSomethingThatMayTakeAWhile
);
// note: you can define the function with duration reporting directly, too
const doSomethingThatMayTakeAWhile = withDurationReporting(
'doSomethingThatMayTakeAWhile',
async (someArg: string, anotherArg: number) => {
/** your logic goes here */
}
)
And here is the wrapper itself:
import { hrtime } from 'process';
const roundToHundredths = (num: number) => Math.round(num * 100) / 100; // https://stackoverflow.com/a/14968691/3068233
/**
* a wrapper which reports how long it took to execute a function, after the function completes
*/
export const withDurationReporting = <R extends any, T extends (...args: any[]) => Promise<R>>(
title: string,
logic: T,
options: {
reportingThresholdSeconds: number;
logMethod: (message: string, metadata?: Record<string, any>) => void;
} = {
reportingThresholdSeconds: 1, // report on anything that takes more than 1 second, by default
logMethod: console.log, // log with `console.log` by default
},
) => {
return (async (...args: Parameters<T>): Promise<R> => {
const startTimeInNanoseconds = hrtime.bigint();
const result = await logic(...args);
const endTimeInNanoseconds = hrtime.bigint();
const durationInNanoseconds = endTimeInNanoseconds - startTimeInNanoseconds;
const durationInSeconds = roundToHundredths(Number(durationInNanoseconds) / 1e9); // https://stackoverflow.com/a/53970656/3068233
if (durationInSeconds >= options.reportingThresholdSeconds)
options.logMethod(`${title} took ${durationInSeconds} seconds to execute`, { title, durationInSeconds });
return result;
}) as T;
};
I designed a simple method for this, using console.time() & console.timeEnd():
measure function definition
function measureRunningTime(func,...args){
const varToString = varObj => Object.keys(varObj)[0]
const displayName = func.name || varToString({ func })
console.time(displayName)
func(...args)
console.timeEnd(displayName)
}
To use it, pass a function without arguments, with arguments binded, or with arguments as the following parameters.
Examples:
let's say I want to check the running time of the simplest searching algorithm - SimpleSearch:
measured function definition (your code here)
const simpleSearch = (array = [1,2,3] ,item = 3) => {
for(let i = 0; i< array.length; i++){
if (array[i] === item) return i;
}
return -1
}
implementation without arguments
measureRunningTime(simpleSearch)
//Prints something like that-> simpleSearch: 0.04ms
implementation with arguments using .bind()
const array = [1,2,3]
const item = 3
measureRunningTime(simpleSearch.bind(null, array, item))
//Prints something like that-> bound simpleSearch: 0.04ms
implementation with arguments without using .bind()
const array = [1,2,3]
const item = 3
measureRunningTime(simpleSearch, array, item)
//Prints something like that-> simpleSearch: 0.04ms
-> Take notice!! this implementation is far from perfect - for example there is no error handling - but it can be used to check the running times of simple algorithms,
Moreover , I'm not an experienced programmer so take everything with a grain of salt 🧂 👌
I had same issue while moving from AWS to Azure
For express & aws, you can already use, existing time() and timeEnd()
For Azure, use this:
https://github.com/manoharreddyporeddy/my-nodejs-notes/blob/master/performance_timers_helper_nodejs_azure_aws.js
These time() and timeEnd() use the existing hrtime() function, which give high-resolution real time.
Hope this helps.
I need this to be cumulative, and to measure different stuff.
Built these functions:
function startMeasuring(key) {
measureTimers[key] = process.hrtime();
}
function stopMeasuring(key) {
if (!measures[key]) {
measures[key] = 0;
}
let hrtime = process.hrtime(measureTimers[key]);
measures[key] += hrtime[0] + hrtime[1] / 1e9;
measureTimers[key] = null;
}
Usage:
startMeasuring("first Promise");
startMeasuring("first and second Promises");
await new Promise((resolve) => {
setTimeout(resolve, 1400);
});
stopMeasuring("first Promise");
stopMeasuring("first and second Promises");
startMeasuring("first and second Promises");
await new Promise((resolve) => {
setTimeout(resolve, 600);
});
stopMeasuring("first and second Promises");
console.log("Measure Results", measures);
/*
Measusre Results {
setting: 0.00002375,
'first Promise': 1.409392916,
'first and second Promise': 2.015160376
}
*/