Timer in javascript - javascript

I have to do a timer in javascript with timing events, the time units should be in milliseconds.
i need something like this:
start_timer
//some code..
stop_timer
//and then show the ms
sorry for my english, and thank you for help!
edit:
i tried this method as test:
var d = new Date();
var time = d.toLocaleTimeString();
var myVar = window.setInterval(function(time){ time -= d.toLocaleTimeString()
return code.value = time.toString();
}, 5000);

The console.time method is perfect but if you want to keep the result in memory you have to use the Date.now method.
let now = Date.now();
for (let i = 0; i < 100000; ++i)
// ...
// Result in milliseconds.
let result = Date.now() - now;
// If you want to show it in a input box.
input.value = result + "ms";

You can use console.time(), for the browsers that support it:
console.time('Stuff')
for (var i = 0; i < 1000; i++) {
// run some code
}
console.timeEnd('Stuff')

Related

How do I constantly refresh a getTime output?

I'm making a little clock using getTime(), but the output won't refresh. I have tried this:
<p id="clock"></p>
var i;
for (i=0; i < 5; i++){
var date = getTime;
var time = time.getHour() + ":" + time.getMinute() + ":" + time.getSecond()
getElementById('clock').innerHTML = time;
}
Though it just keeps my tab in a constant state of loading. How do I fix this? Thanks!
Just move your code inside setInterval()
let i = 5;
const timer = setInterval(() => {
var date = getTime;
var time = time.getHour() + ":" + time.getMinute() + ":" + time.getSecond()
getElementById('clock').innerHTML = time;
i--;
if (i < 0) {
clearInterval(timer)
}
}, 1000);
So setInterval() lets your code run asyncrounously, that means it doesnt block the rest of the execution, because it runs "seperately" (I would like to describe it better, but my english skills are lacking).
setInterval runs your code every 1000 ms (as specified) forever, unless you dont clear it with clearInterval(). If you want to make a timer it is quiet useful.
this () => {} is an arrow function. You can also use function(){}, if you want, in this case it makes no difference.
Here is the w3schools reference for setInterval(): https://www.w3schools.com/jsref/met_win_setinterval.asp
and here is the MDN reference to asynchronous javascript: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous
Good luck with your project ;)
I hope this helps
setInterval (function refresh(){
var fecha = new Date();
var hora = fecha.getHours();
var minutos = fecha.getMinutes();
var segundos = fecha.getSeconds();
var textoHora = `
${hora}:${minutos}:${segundos}
`;
document.getElementById('clock').innerHTML = textoHora;
}, 1000);

Measure process time with Node Js?

I would like to do the following:
console.time("processA");
for(let i; i < 10000; i++) {
// Just to simulate the process
}
console.timeEnd("processA");
but I want to capture the time end and use my own logger of information with it.
Is it possible to handle the console output of the timeEnd?
How can I measure the time interval of a process in nodejs?
Since you are targeting nodejs, you can use process.hrtime as stated in the docs
The process.hrtime() method returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array, where nanoseconds is the remaining part of the real time that can't be represented in second precision.
So you can measure timings up to nanosecond, something that console.time can't, as you can see in your example console.time or Date difference measures 0s.
For example:
const NS_PER_SEC = 1e9;
const MS_PER_NS = 1e-6
const time = process.hrtime();
for (let i; i < 10000; i++) {
// Just to simulate the process
}
const diff = process.hrtime(time);
console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
console.log(`Benchmark took ${ (diff[0] * NS_PER_SEC + diff[1]) * MS_PER_NS } milliseconds`);
Since I'm using timers in multiple places, I wrote a simple class based on Alex's answer:
const t = new Timer('For Loop')
// your code
t.runtimeMs() // => 1212.34
t.runtimeMsStr() // => 'For Loop took 1232.34 milliseconds'
Here's the code:
class Timer {
// Automatically starts the timer
constructor(name = 'Benchmark') {
this.NS_PER_SEC = 1e9;
this.MS_PER_NS = 1e-6
this.name = name;
this.startTime = process.hrtime();
}
// returns the time in ms since instantiation
// can be called multiple times
runtimeMs() {
const diff = process.hrtime(this.startTime);
return (diff[0] * this.NS_PER_SEC + diff[1]) * this.MS_PER_NS;
}
// retuns a string: the time in ms since instantiation
runtimeMsStr() {
return `${this.name} took ${this.runtimeMs()} milliseconds`;
}
}
Starting from Node v8.5, you can use browser-equivalent performance.now() which is easier to use than process.hrtime because it outputs the time in milliseconds directly, therefore you don't have to do a conversion as in process.hrtime
const { performance } = require("perf_hooks");
const start = performance.now();
doSomething();
const end = performance.now();
console.log(`time taken: ${end - start}ms`);
You can find more info from Node.js Docs on Performance API.
var startTime = new Date();
for(let i; i < 10000; i++) {
// Just to simulate the process
}
var endTime = new Date() - startTime;
You will get the total time that it takes to complete the operation
See here https://alligator.io/js/console-time-timeend/
var begin=console.time('t');
for(let i; i < 100000; i++) {
// Just to simulate the process
}
var end= console.timeEnd('t');
var timeSpent=(end-begin) / 1000 + "secs";

Using timer behind multiple alerts and prompts

I have a game that I am making using only pure javascript. Instead of a GUI, It is more like the old command line games and uses a prompt for input.
One of the main components of it is the Clock, which is expressed in hours, and can be checked with the commmand "time" and tells them the value of the variable "time". Here is the code:
var timestrt = 1;
var timer = setInterval(function(){timestrt++;return timestrt;}, 86000); var time = timestrt;
After testing it, I realized that the clock was not changing. So I set it to 10 seconds instead of 86 to be sure that I was waiting long enough, and it still did not want to work
I know that it is probably caused by the prompt and constant alerts, but I am not sure even where to start for a workaround.
Any ideas?
Edit: is it possible to either
1. retrieve the timer from an external page
2. comparing it to an actual clock in real time or 3. Using a animated gif clock in the background and calculating the location of certain pixels as time?
Don't use the native prompts and dialogs, since they stop the script execution time. Instead use simulated ones, for example jQuery IU has prompts and dialog boxes that do not stop execution. Here is an example of that:
$(function() {
$( "#dialog" ).dialog();
var timestrt = 1;
var timer = setInterval(function(){
timestrt++;
var time = timestrt;
$("#time").text(time);
}, 1000);
});
Here is my workaround:
This code is called before the prompt is started:
function initTime() {
var now = new Date();
stS = now.getSeconds();
stM = now.getMinutes();
stH = now.getHours();
}
This is called after the prompt is done:
function computeTime() {
var now = new Date();
var reS = now.getSeconds();
var reM = now.getMinutes();
var reH = now.getHours();
var elapS = reS - stS;
var elapM = reM - stM;
var elapH = reH - stH;
if (elapM < 0) {
reM = reM + 60;
elapM = reM - stM;
}
if (elapS < 0) {
reS = reS + 60;
elapS = reS - stS;
}
Then I convert it to seconds to make it easier to check against:
var finalH = elapH * 3600;
var finalM = elapM * 60;
var finalS = finalM + elapS + finalH;
And check/change the time variable based on how many sets of 86 seconds has passed:
if (finalS > 86 && finalS < 172) {
time = 1;
}
if (finalS > 172 && finalS < 258) {
time = 2;
}
if (finalS > 258 && finalS < 344) {
time = 3;
}
if (finalS > 344 && finalS < 430) {
time = 4;
}
if (finalS > 430 && finalS < 516) {
time = 5;
}
if (finalS > 516) {
time = 6;
alert('5 A.M.');
alert('A clock is chiming...');
alert('6 A.M.');
playing = false;
alert('Thanks for playing! Goodbye!');
}
And that is my alternative to using a setinterval/timer behind multiple prompts and alerts. The last part probably wasn't needed, but since it answered my original question I included it.

jQuery setInterval giving Invalid argument

Good morning, I created a function that gets all the USA timezone times and returns them to me highlighting which timezone you are in. The issue is I want it to run every minute. When I use the setInterval function I keep getting a javascript error saying 'invalid argument'. Here is my code in jsFiddle http://jsfiddle.net/Qg2eL/
// Timezone
var arrTime = new Array();
var arrZone = new Array("ET","CT","MT","PT");
var getTimeZones = setInterval(timeZone(),60000);
function timeZone(){
var location = 0;
var current_date = new Date();
var offset = parseInt(-current_date.getTimezoneOffset() / 60);
switch(offset){
case -5:
location = 0;
break;
case -6:
location = 1;
break;
case -7:
location = 2;
break;
case -8:
location = 3;
break;
}
arrTime.length = 0;
for(var x=5; x<9; x++){
var current_date = new Date();
var utc_hour = current_date.getUTCHours() - x;
var utc_minutes = current_date.getUTCMinutes().toString();
var dd = "AM";
if(utc_hour >= 12){
utc_hour = utc_hour - 12;
dd = "PM";
}
if(utc_hour == 0){ utc_hour = 12; }
utc_minutes = utc_minutes<10?"0"+utc_minutes:utc_minutes;
var formattedTime = utc_hour+":"+utc_minutes+" "+dd;
arrTime.push(formattedTime);
}
var strHTML = "";
strHTML += "<ul>";
for(var x=0; x<arrTime.length; x++){
strHTML += "<li>"+arrZone[x]+": "+arrTime[x]+"</li>";
}
strHTML += "</ul>";
$('.timezoneHolder').html(strHTML);
$('.timezoneHolder ul li:nth-child('+(location+1)+')').css({
"color":"lime",
"font-weight":"bold"
});
}
Very common mistake is that you're not passing the function to be executed but actually calling it in this line:
var getTimeZones = setInterval(timeZone(),60000);
Rather:
var getTimeZones = setInterval(timeZone,60000);
PS. tested in Chrome and IE. and no invalid argument popped up.
Edit: The reason you're not seeing it pop up after making your change is because it will only be executed after 60 seconds, so you should just call the function after your setInterval and will be executed every 60 seconds afterwards.
var getTimeZones = setInterval(timeZone,60000);
timeZone();
The setInterval function runs its own "callback" you could say. The syntax is just a little off. Try this:
var getTimeZones = setInterval(function() {
timeZone();
},60000);
This syntax basically says, every 60000 milliseconds (or 60 seconds) perform the function inside of the interval. In this case the setInterval function calls your function.
Hope this helps.
var getTimeZones = setInterval(timeZone,60000);
remove the brackets! :)

Simple jQuery Count Up timer help please

Trying to make a simple count up timer in jQuery... this sort of works but is adding the numbers to the end of '0000' and I want it to go '0001' '0002' '0003' etc...
This is all happening in the jQuery onReady scope.
var i = '0000'
var timer = function doSomething ( )
{
i = i+= 1
$('.counter').text(i);
console.log(i);
}
setInterval (timer, 1000 );
Your "i" variable needs to be an integer. You can format it how you like when you want to print it somewhere.
$(document).ready(function() {
var i = 0;
var target = $('.counter');
var timer = function doSomething ( )
{
i++;
var output = pad(i,4);
target.text(output);
console.log(output);
}
setInterval (timer, 1000 );
});
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}​
Your current code is appending to a string, not addition to a number. It essentially looks like
i = '0000' + 1, i = '00001' + 1, i = '000011' + 1 ...
and so on. You'll need to keep it integer based to continue adding to the number. Here's an example with the formatting it looks like you wanted.
var pad = function(n) { return (''+n).length<4?pad('0'+n):n; };
jQuery.fn.timer = function() {
var t = this, i = 0;
setInterval(function() {
t.text(pad(i++));
}, 1000);
};
$('#timer').timer();
http://jsfiddle.net/jDaTK/
I would do something more like this:
// Make sure Date.now exists in your environment
Date.now = Date.now || function () { return Number(new Date()); };
var time = 0,
start = Date.now(),
intervalId;
intervalId = setInterval(function () {
var seconds, display;
// get the exact time since the timer was started
time = Date.now() - start;
// get the number or seconds, rounded down
seconds = Math.floor(time / 1000);
display = '' + seconds;
// pad the beginning of your display string with zeros
while (display.length < 4) {
display = "0" + display;
}
console.log(display);
}, 100);
setInterval is not exact. This code ensures that while the display could be up to nearly a second off (in theory), the actual time you are tracking is always the exact amount of time that has elapsed since you started the timer. But this code would update the display about once every tenth of a second, so it's not likely to ever be off more than a few milliseconds.
From here you can figure out smarter ways to update the display to ensure you have the level of accuracy you need. If this needs to be pretty accurate, then you could make sure you are displaying to the tenth of the second.
I really recommend the jQuery CountUp plugin. I tried a number of Javascript counters and this was one of the easiest to implement and came with lots of goodies:
<script type="text/javascript">
$(document).ready(function(){
$('#counter').countUp({
'lang':'en', 'format':'full', 'sinceDate': '22/07/2008-00::00';
});
});
</script>
<div id="counter"></div>

Categories