How to add milliseconds to this javascript reverse count down timer counter - javascript

numberOfSeconds=1*60,
r=document.getElementById('clock');
var t = setInterval(function(){
numberOfSeconds--;
var minutes=Math.floor(numberOfSeconds/60),seconds=(numberOfSeconds%60)+'';
r.textContent='Registration closes in '+minutes+':'+(seconds.length>1?'':'0')+seconds;
if (numberOfSeconds <= 0) {
clearInterval(t);
alert('boom');
}
},1000);
html section
<div id="clock"></div>
how i can add milliseconds to this reverse count down timer/counter script.
i want it like 00:00:00 <== milliseconds in last.
}},1000 / 20);
However above little change in last of script made seconds into milliseconds but i can't figure out how i can adjust it with seconds like MM:SS:MS 00:00:00
Any Help will be appreciated..!

That setInterval will have to be set to 1 (ms), if you need to see the milliseconds. 1000ms = 1s. So I believe MM:SS:MS would look more like 00:00:000.

I do not think it's possible. i did a test and the results show that js cannot be as fast to set 1millisecond to setInterval. setting it to 1ms - 15ms will output the same results.
normaly the code below should work the way you wanted.
var m = 60*1000, r = document.getElementById("clock");
var t = setInterval(function () {
m--;
var min = Math.floor(m / 60000),
sec = Math.floor((m % 60000) / 1000);
mil = (m % 60000) % 1000; r.innerHTML = min + ":" + sec + ":" + mil;}, 1)
Maybe the problem comes from my computer (maybe it is slow).
if you ever want the test script, tell it in comment so i will give it to you in order you'll test it by yourself

Related

JavaScript Freezes Browser

I'm trying to make a countdown timer for each row of a table based on a hidden field containing the ammount of seconds to finish. Here is what I have done so far:
function countdownProcedure() {
var interval = 1000;
var i = 0;
var seconds;
$(".rfqTbl tr").each(function() {
if(i > 0) {
seconds = $(this).find("#sqbTimestamp").text();
var days = Math.floor(seconds / (60*60*24));
seconds -= days * 60 * 60 * 24;
var hours = Math.floor(seconds / (60*60));
seconds -= hours * 60 * 60;
var minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
if(days < 1) { days=""; }
$(this).find("#countDown").html(days + "<pre> Days</pre> " + hours + "<pre>:</pre>" + minutes + "<pre>:</pre>" + seconds);
if(days > 1) {
$(this).find("#countDown").css({
'color':'#2A7F15',
'font-weight':'bold'
});
};
if(days < 1) {
$(this).find('#countDown').css('color','red');
$(this).find('#countDown pre:nth-of-type(1)').css('display','none');
}
if(seconds < 10) {
$(this).find("#countDown").append(" ");
};
if(minutes < 60){ interval = 1000; };
}
i++;
});
setInterval(countdownProcedure,interval);
};
However, my problem is that I'm trying to get this function to run (realistically every second or 30) so that the time shown would update and hence 'countdown'. The problem I am having is in firefox and safari the browsers are just hanging after the first countdown and chrome is doing nothing (I guess it has a safe guard to prevent it from hanging).
Any help would be much appreciated!
You are running a multitude of setInterval() calls, so the event queue gets crowded with your function.
I think, what you mean is more like setTimeout() at the end of your function.
function countdownProcedure(){
// all your logic
setTimeout(countdownProcedure,interval);
};
The difference is, that setInterval() will run your code every x seconds, until you tell it to stop.
setTimeout() on the other hand, just runs your code once after x seconds.
Change all ids for clases Ex: #sqbTimestamp for .sqbTimestamp
in an HTML document, should exists only 1 element with some id, if you set multiple elements with same id, unexpected results (as browser hanging) can occurrs.
Also, you are setting days="" and then do the following compare if (days > 1)
I think your algorithm is wrong. You are recursively setting intervals which are calling themselves every time and setting new intervals and so on...
You must change your algorithm a bit to get it clean.

Count-Up Timer on each page load from 0

I want to implement a count-up timer JS code that starts counting at each load page from 0. The code which I've now is like this:
var secondsTotal = 0;
setInterval(function() {
++secondsTotal;
var minutes = Math.floor(secondsTotal / 60);
var seconds = Math.floor(secondsTotal) % 60;
var milliseconds = Math.floor(secondsTotal) % 1000;
document.getElementById('counter').innerHTML = minutes + ":" + seconds + "." + milliseconds;
}, 1000);
The output format should be: 00:00.0
mm:ss.ms
So, how to output the result like above format (minutes and seconds should be exactly printed in two digits format)?
If you want to do it per-page, you're almost there. Right now, your code does not allow you to track milliseconds, as your setInterval runs every second. What I would recommend instead is something like this:
(function() {
var counter = 0,
cDisplay = document.getElementById("counter");
format = function(t) {
var minutes = Math.floor(t/600),
seconds = Math.floor( (t/10) % 60);
minutes = (minutes < 10) ? "0" + minutes.toString() : minutes.toString();
seconds = (seconds < 10) ? "0" + seconds.toString() : seconds.toString();
cDisplay.innerHTML = minutes + ":" + seconds + "." + Math.floor(t % 10);
};
setInterval(function() {
counter++;
format(counter);
},100);
})();
This does a couple of things to allow your code to run 10 times per second:
The output element, #counter, is cached and not retrieved every iteration
The formatting is kept to arithmetic operations only - modulo and division.
This now also adds leading zeroes.
If you would like to keep this counter running page-per-page, consider using document.cookies to pass the final value from page to page.
Fiddle
This serves as a good first version. However, you may want to:
Pause/re-start your timer
Reset your timer
Have multiple timers
For this reason, I will add a slightly more complex form of the above code, which will allow you to manage multiple timers. This will make use of a few OO concepts. We will use a TimerManager object to "host" our timers, and each Timer object will have a link to the manager.
The reason for this is because every timer will depend on the same setInterval() by doing it this way, rather than to have multiple setInterval() calls. This allows you to cut down on wasted clock cycles.
More on this in about 5 minutes!
Counting seconds that way isn't guaranteed to be accurate. The setInterval method can drift on you based upon the JS engine's ability to complete its other tasks. Not sure what your use case is, such as how long you expect to count up, but it's worth taking note of. See Will setInterval drift? for a detailed explanation.
I'd recommend you check out the momentjs plugin # http://momentjs.com/ and update your code to something like the following
var startTime = moment();
var el = document.getElementById('counter');
setInterval(function() {
var ms = moment().diff(startTime),
min = moment.duration(ms).minutes(),
sec = moment.duration(ms).seconds();
ms = moment.duration(ms).milliseconds();
min = (min < 10) ? "0" + min.toString() : min.toString();
sec = (sec < 10) ? "0" + sec.toString() : sec.toString();
ms = ms.toString().substring(0,2); // change this if you want to expand ms counter display
el.innerHtml = min + ":" + sec + "." + ms;
}, 50);
You're free to update the interval, and your milliseconds display without adjusting your calculations.

Greasemonkey script fails passing date/time to GM_setValue

I'm writing a Greasemonkey script where I want to know when it was last run. To do this, I wanted to store the current time with GM_setValue and compare that time to the time when the script is run again.
However, it seems that the Date().getTime() results won't pass to GM_setValue. For instance if you run:
var newtime = new Date().getTime();
GM_setValue('lastrun', newtime);
alert(GM_getValue('lastrun'));
There's obviously errors since the alert box won't pop up. However if you replace the first line with:
var newtime = 1;
you then get 1 returned in the alert box like you would expect.
That pretty much just isolates the date format causing the issue here. Any ideas on how to deal with this, or better ways to save dates between times a script has run?
I had a similar issue. The number is too large to be stored as a firefox cookie value. My solution was to limit the precision to the second (divide by 1000, drop remainder) and subtract 43 years (1356998400 seconds) to bring the date measured from to Midnight Jan 1st 2013 so my code looks like this:
var time = Math.floor((new Date().getTime() / 1000) - 1356998400);
GM_setValue("runTime", time);
and the retrieval looked like:
var time = GM_getValue("runTime", 0);
if (time != 0) {
var cur = Math.floor((new Date().getTime() / 1000) - 1356998400);
var cur = cur - time;
var sec = cur % 60;
var min = Math.floor(cur / 60);
console.log("Script took " + min + ":" + sec);
}

Unix timestamp to seconds in javascript

I'm trying to do a program which executes after 15 minutes of being in the page. My problem is how to get the exact number to add on the timestamp which is stored in a cookie.
I need a function to convert seconds into timestamps or anything that can make the action execute after 15 minutes. I don't really know how much time is 1792939 which I place in the code below.
setInterval("timer()",1000);
$.cookie("tymz", time);
function timer(){
var d = new Date();
var time = d.getTime();
var x = Number($.cookie("tymz")) + 1792939;
//alert('Cookie time: ' + x + '\nTime: ' + time);
if(time > x){
alert('times up');
}else{
//alert('not yet\n' + 'times up: ' + x + '\ntime: ' + time);
}
}
How about using setTimeout(..)?
<script type="text/javascript">
function myFunc()
{
alert("I will show up 15 minutes after this pages loads!");
}
setTimeout("myFunc()",60*15*1000);
</script>
Check this: http://www.w3schools.com/js/js_timing.asp
unix timestamp are second from epoch (1/1/1970) so if you want to execute some code after 15 minutes just record the time when the page is loaded then every second calculate how many seconds are passed from page load. When the difference between current time and page load time is greater than 15*60*1000 you can execute your code.
var pageLoad = new Date().getTime();
function tick(){
var now = new Date().getTime();
if((now - pageLoad) > 15*60*1000) executeYourCode();
}
setInterval("tick()",1000);
Remeber that javascript return time in millisecond
Hope this helps
If the number is seconds since 1/1/1970 00:00:00, then you can convert '1792939' to a javascript date by multiplying by 1,000 and passing to Date:
var d = new Date(1792939 * 1000) // Thu Jan 22 1970 04:02:19
Currently it is about 1311428869 seconds since 1/1/1970. So if you have a value for seconds, then you can use setInterval to run a function 15 minutes after that:
var seconds = ?? // set somehow
var start = new Date(seconds * 1000);
var now = new Date();
var limit = 15 * 60 * 1000;
var lag = now - start + limit;
// Only set timeout if start was less than 15 minutes ago
if ( lag > 0 ) {
setTimeout( someFn, lag);
}
Provided the current time is less than 15 minutes from the start time, the function will run at approximately 15 minutes after the start time. If the system is busy when the time expires, the function should be run as soon as possible afterward (usually within a few ms, but maybe more).
works without server or cookie (and all browser after IE7)
Looks like you use jQuery, so you might as well use jQuery.now() insted
var firstVisit = localStorage['firstVisit'] = localStorage['firstVisit'] || $.now();
function myFunc(){
alert("I will show up 15 minutes after this pages loads!");
}
setTimeout(myFunc, parseInt(firstVisit) - $.now() + 1000 * 60 * 15);

Javascript/Jquery Refresh timer

I have a simple system that refreshes a div every few seconds:
$(document).ready(function() {
$("#nownext").load("response.php");
var refreshId = setInterval(function() {
$("#nownext").load('response.php?randval='+ Math.random());
}, 20000);
});
Now, because of what the content is, it is more likely to update on the hour, or at half past. (Though not always). What I'd like to do it make the system refresh MORE often between a few minutes before and after the hour (and half past), just to make it more precise.
Is this possible/how would I do it without stressing out the client's computer too much?
Use setTimeout instead of setInterval so you can dynamically alter the timing of the next interval. I'm not sure what the performance implications of creating and checking the Date() object ever millisec in the "Fast" period would be, but you could always tune that frequency up closer to every second if its an issue.
start_timer = function(timing) {
var timer, d = new Date(), min = d.getMinutes(),
timeout = 20000; /* slow timeout */
if((min >= 28 && min <= 30) || min >= 58) {
timeout = 100; /* fast timeout */
}
timer = setTimeout(start_timer, timeout);
// Call your code here.
};
$(document).ready(function() {
start_timer();
});
Since the interval itself is going to be dynamic, you're going to have to use setTimeout instead.
Something like this (untested):
$(document).ready(function() {
$("#nownext").load('response.php?randval='+ Math.random());
var minutes = new Date().getMinutes(), interval = 60*10*1000; // default 10 mins
if (minutes <= 10 || (minutes > 30 && minutes < 35) || minutes > 50) {
// update once-per-minute if within the first/last 10mins of the hour, or 5mins within the half hour
interval = 60*1000;
}
setTimeout(arguments.callee, interval);
});

Categories

Resources