Suppose you wanted to set a timer to whatever time you want will be displayed in the form 00:00:00 minutes, seconds, and hundredths. How would you go about doing so? Please any help is greatly appreciated.
Here is the link in JSFiddle:
https://jsfiddle.net/mxpuejvz/2/
function decrement(){
var time = 600;
var mins = parseInt((time / 100) / 60);
var secs = parseInt((time / 100) % 60);
var hundredths = parseInt(time % 100);
if(mins < 10) {
mins = "0" + mins;
}
if(secs < 10) {
secs = "0" + secs;
}
if(hundredths < 10) {
hundredths = "0" + hundredths;
}
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + hundredths;
if (hundredths === 0){
if(time ===0){
clearInterval(countdownTimer);
document.getElementById("output").innerHTML = "Time's Up.";
}else{
time--;
}
var countdownTimer = setInterval('decrement()', 10)
}
}
}
Three issues appear to need attention.
"time to go" needs to be stored outside the screen update function and decremented or calculated each time the screen is updated.
using parseInt to convert numbers to integer numbers is regarded as a hack by some. Math.floor() or integer calculation can be alternatives.
Timer call backs are not guaranteed to made exactly on time: counting the number of call backs for a 10msec time does not give the number of 1/100ths of elapsed time.
The following code is an example of how it could work, minus any pause button action.
var countdownTimer;
var endTime;
var counter = 0; // ** see reply item 3. **
function startCountDown( csecs) // hundredths of a second
{ endTime = Date.now() + 10*csecs; // endTime in millisecs
decrement();
countdownTimer = setInterval(decrement, 10);
counter = 0; // testing
}
function decrement()
{ var now, time, mins, secs, csecs, timeStr;
++ counter; // testing
now = Date.now();
if( now >= endTime)
{ time = 0;
timeStr = "Times up! counter = " + counter;
clearInterval( countdownTimer);
}
else
{ time = Math.floor( (endTime - now)/10); // unit = 1/100 sec
csecs = time%100;
time = (time-csecs)/100; // unit = 1 sec
secs = time % 60;
mins = (time-secs)/60; // unit = 60 secs
timeStr =
( (mins < 10) ? "0" + mins : mins) + ":" +
( (secs < 10) ? "0" + secs : secs) + ":" +
( (csecs < 10) ? "0" + csecs : csecs);
}
document.getElementById("output").innerHTML=timeStr;
}
The argument to startCountDown gives the number of 1/100ths of second for the count down. If the counter result is the same as the argument,try swapping browser tabs and back again during the countdown.
HTML to test:
<button type="button" onclick="startCountDown(600)">start</button>
<div id="output">
</div>
Related
I have searched all over internet a lot but could not find solution.
I want a timer with descending order with minutes, seconds and milliseconds. i.e. 05:59:999 -> 5 Minutes, 59 Seconds, 999 Milliseconds.
Below is my code which give me just minutes and seconds :
var countdownTimer = '';
var upgradeTime = 300; // total sec row from the table
var seconds = upgradeTime;
function timer()
{
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
document.getElementById('timer1').innerHTML = pad(minutes) + " : " + pad(remainingSeconds);
document.getElementById("timer1").style.border = "1px solid";
document.getElementById("timer1").style.padding = "4px";
}
function pad(n)
{
return (n < 10 ? "0" + n : n);
}
$('#acstart').on('click', function(e) // Start the timer
{
clearInterval(countdownTimer);
countdownTimer = setInterval('timer()', 1000);
});
I found fiddle with seconds and milliseconds here is the link :
http://jsfiddle.net/2cufprgL/1/
On completion of the timer I need to call other action.
Thanks
Using the fiddle you included, you only need to update the displayCount function to get the result you want.
function displayCount(count) {
let res = Math.floor(count / 1000);
let milliseconds = count.toString().substr(-3);
let seconds = res % 60;
let minutes = (res - seconds) / 60;
document.getElementById("timer").innerHTML =
minutes + ' min ' + seconds + ' s ' + milliseconds + ' ms';
}
Note that your fiddle has the correct approach to countdown, everytime the timer ticks it measures the actual time left it doesn't assume that the timer was 'on time'.
I wouldn't call this clean. But I did follow through using your code. I did change it to recursive setTimeout() though.
What I did is call the interval faster than 1000ms, set a specific speed variable and then properly decrement seconds while checking for a flag when seconds becomes 0, this flag then calls stopTimer().
var countdownTimer = '';
var upgradeTime = 3; // total sec row from the table
var seconds = upgradeTime;
var milliseconds = seconds * 1000;
var speed = 50; //interval speed
function timer()
{
milliseconds = (seconds * 1000) - speed; //decrement based on speed
seconds = milliseconds / 1000; //get new value for seconds
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = (seconds % 60).toFixed(3);
if(seconds <= 0){ stopTimer(); return; } //sets a flag here for final call
document.getElementById('timer1').innerHTML = pad(minutes) + " : " + pad(remainingSeconds);
document.getElementById("timer1").style.border = "1px solid";
document.getElementById("timer1").style.padding = "4px";
setTimeout('timer()', speed);
}
function stopTimer(){
clearTimeout(countdownTimer);
console.log("IT HAS BEEN DONE");
document.getElementById('timer1').innerHTML = "00 : 00.000"
}
function pad(n)
{
return (n < 10 ? "0" + n : n);
}
clearTimeout(countdownTimer)
countdownTimer = setTimeout('timer()', speed);
<div id="timer1"></div>
Something that sorta works logically right now. It's a tad unstable because of what I was trying to do. https://codesandbox.io/s/8xr1kx8r68
Momentjs with Countdown library - its a little outdated and unmaintained but looks like it does something like what you want.
https://github.com/icambron/moment-countdown
http://countdownjs.org/readme.html
recently i implemented a count timer for my shopping website that sets a limit of 24 hours when they create an order and not check out with a payment,so that counter reminds him/her that have to make a payment. The timer that is in our table is the start time and is adjusted by the current time up to 24 hours - after that, the order is cancelled.
Now i have a problem, when i reload the page the counter restarts from 24 hours this is my code
<script type="text/javascript">
function startTimer(duration, display) {
var start = '<?php echo $pending_order_date;?>';
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
if(minutes >= 60){
hours = (minutes / 60) | 0;
minutes = (minutes % 60) | 0;
}else{
hours = 0;
}
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var twentyfourhour = 60 * 60 *24,
display = document.querySelector('#time');
startTimer(twentyfourhour, display);
};
</script>
Please see my code, i get the timestamp in php from my table and the count.
Your help would be appreciated.
You need to store your left off duration somewhere. localStorage seems to be better fit
function startTimer(duration, display) {
var start = '<?php echo $pending_order_date;?>';
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
if(minutes >= 60){
hours = (minutes / 60) | 0;
minutes = (minutes % 60) | 0;
}else{
hours = 0;
}
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
localStorage.setItem('timer', diff);
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var twentyfourhour = 60 * 60 *24,
display = document.querySelector('#time');
var timePassed = localStorage.getItem('timer');
startTimer((typeof timer!=='undefined' ? timer : twentyfourhour), display);
};
so each time your duration changes, it will update localStorage timer value. when you reload page, it will look for timer item in localStorage and will get that value, if it doesn't exist then will use 24 hrs. you may also add a controller to remove timer once it is expired, and store it with the order number or something so you can use multiple values. but this should give you an idea.
I am writing for web exam page ,in there I have to set 30 minutes to exam time.So I used onload and settimeout function to check if 30 minutes over,the question page is close and go to finish page.I want to add current minutes 30.But it's doesn't work,don't go to finish.php.!
<body onload="time()">
<!-- question code -->
<div id="time"></div><!-- show time -->
</body>
JS
<script>
function time(){
var j = new Date();
var hr = j.getHours();
var sec = j.getSeconds();
var min = j.getMinutes();
var m = min + 30;//set 30 minutes exam times
if (m === min) {
location.href = "finish.php";
}
document.getElementById('time').innerHTML = hr + ":" + min + ":" + sec;
setTimeout(function() {
time()
}, 1000);
}
</script>
Try with this
function time(){
setTimeout(function() {
location.href = "finish.php";
}, 30*60*1000);
setInterval(function() {
var j = new Date();
var hr = j.getHours();
var min = j.getMinutes();
var sec = j.getSeconds();
document.getElementById('time').innerHTML = hr + ":" + min + ":" + sec;
}, 1000);
}
function time() {
var time = 60 * 1; //Replace 1 with 30 minutes
var minutes, seconds;
setInterval(function () {
minutes = parseInt(time / 60)
seconds = parseInt(time % 60);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById('time').innerHTML = minutes + ":" + seconds;
time--;
if (time < 0) {
location.href = "finish.php";
}
}, 1000);
}
<body onload="time()">
<!-- question code -->
<div id="time"></div><!-- show time -->
</body>
Your are assigning new value to m every timeout. you should initialize, m only once.
also minute goes from 0-59 so you cant always check for it is equal to m + 30, thats wrong way of doing it
being said that its always better to do this timeout at server side, at client side there are enough ways to cheat around it
so I've been tyring to debug my script for my pomodoro(tomato) clock. What I want this script to do is it will recieve input(in minutes). Right now what my script is doing is counting down by 5 instead of 1 seconds. Also it will not display the minutes like I want it too.
I made the script in a logical way to log to console and test it. What I see in the console is it displays every second, but it displays 5 seconds every second if that makes sense. Here is the jsbin: https://jsbin.com/gigohajawo/3/edit?js,consolehttps://jsbin.com/gigohajawo/3/edit?js,console
Here is the code, any help would be appreciated!!!
//makes sure the page is loaded first
$(document).ready(function() {
//global variables
//grabs text of an id and converts it to an int
var countMin = 5;
var count1 = 60;
//when button id "but" is clicked...
//while page is up, it keeps track each second that has passed
for(; countMin >=0;countMin--){
var counter1 = setInterval(function(){
//calls timer function to count down
count1 = Timer(count1,counter1,countMin);
},1000);
count1 =60;
}
//counts down
function Timer(count,counter,minutes){
count--;
//once it hits 0 seconds, the interval will stop counting
if(count <=0){
clearInterval(counter);
return count;
}
//displays the countdown
if(minutes < 10){
if(count < 10){
console.log("0:0" + count);
} else {
console.log("0:" + count);
}
}else if(minutes > 0 && minutes < 10){
if(count < 10){
console.log("0" + minutes +":0" + count);
} else {
console.log("0"+minutes+":" + count);
}
} else{
if(count < 10){
console.log(minutes+":0" + count);
} else {
console.log=minutes+":" + count;
}
}
return count;
}
});
This JSBin seems to do what you intended.
The code:
//makes sure the page is loaded first
$(document).ready(function() {
//global variables
//grabs text of an id and converts it to an int
var count1 = 120;
// Call a function every 1000 milliseconds (1 second)
var counter1 = setInterval(function() {
count1 = Timer(count1, counter1);
}, 1000);
//counts down
function Timer(count,counter){
// Decrement the seconds counter
count--;
// Get the minutes and seconds in whole numbers
var minutes = Math.floor(count / 60);
var seconds = count % 60;
// Once it hits 0 seconds, the interval will stop counting
if(count <=0){
clearInterval(counter);
}
// Pads the seconds with a 0
if (seconds < 10) {
seconds = "0" + seconds;
}
// Pads the minutes with a 0
if (minutes < 10) {
minutes = "0" + minutes;
}
//displays the countdown
console.log(minutes + ":" + seconds)
return count;
}
});
Please note:
Since you have defined count1 as a global variable you do not need to pass it into Timer
The same goes for counter1
If I was rewriting it I would do something like this:
//makes sure the page is loaded first
$(document).ready(function() {
var timeInSeconds = 120;
var timeCounter = setInterval(function() {
timeInSeconds--;
// If we hit 0 seconds clear the timer
if (timeInSeconds <= 0) {
clearInterval(timeCounter);
}
// Display the current time
displayTime();
}, 1000);
function displayTime(){
// Get the minutes and seconds in whole numbers
var minutes = Math.floor(timeInSeconds / 60);
var seconds = timeInSeconds % 60;
// Pad with zeros using the Ternary operator
seconds = (seconds < 10) ? "0" + seconds : seconds;
minutes = (minutes < 10) ? "0" + minutes : minutes;
// Display the countdown
console.log(minutes + ":" + seconds)
}
});
I have a countdown script that counts down until a certain day that is specified. I want it to just count down 24 hours every time its loaded but can't seem to get it to happen.
thanks
http://pastebin.com/zQ4ESHuG
var timeInSecs;
var ticker;
function startTimer(secs){
timeInSecs = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs>0) {
timeInSecs--;
}
else {
clearInterval(ticker); // stop counting at zero
//startTimer(60 * 60 *24 * 5); // and start again if required
}
var days = Math.floor(secs/86400);
secs %= 86400;
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
var result = ((hours < 10 ) ? "0" : "" ) + hours + ":" + ( (mins < 10) ? "0" : "" ) + mins
+ ":" + ( (secs < 10) ? "0" : "" ) + secs;
result = days + " Days: " + result;
document.getElementById("countdown").innerHTML = result;
}
Solved it.
Thanks everyone.