I'm trying to create a javascript counter that starts at 25 minutes and ends at 0. the idea is to show the minutes/seconds as a countdown clock on the page (my target div is called 'txt'). But I'm not getting my desired result - the timer does not subtract each time the function is run (every ms). Any ideas on where I'm going wrong? Code is below:
function countdown() {
var target = 1500000; // 25 mins
var current = 1000; // 0 secs
for (var i=0; i<5; i++) {
var diff = target-current; // calculates the 25 minutes
var min = Math.floor(diff/1000/60); //gets mins
var sec = (diff/1000) % 60; // gets secs
current = current+1000;
document.getElementById("txt").innerHTML = min + ":" + sec;
var t = setTimeout(countdown, 2500);}
}
}
You need to define current outside of your function. Currently you are resetting it to 1000 every time the function is run.
here you go:
var target = 1500000; // 25 mins
var current = 0; // 0 secs
function countdown() {
current += 1000;
var diff = target-current; // calculates the 25 minutes
var min = Math.floor(diff/1000/60); //gets mins
var sec = (diff/1000) % 60; // gets secs
document.getElementById("txt").innerHTML = min + ":" + sec;
if (diff > 0)
setTimeout(countdown, 1000);
}
countdown();
JSFiddle with running example: https://jsfiddle.net/epcmw0uc/5/
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
I am designing a javaScript countdown for 3 hours using the below code
<div id="timer"></div>
<script type="text/javascript">
var count = 10800;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
but the only issue I am having here is whenever I refresh the page the countdown starts all over again. I want it to resume from where it stopped.
You need to store the data into some persistent storage method, such as cookies, the browsers localStorage, or write data out to an external data source (such as a database through an API). Otherwise the session data is lost between browser refreshes.
For example, if you wanted to use localStorage:
<script type="text/javascript">
// properties
var count = 0;
var counter = null;
window.onload = function() {
initCounter();
};
function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}
function setLocalStorage(key, val) {
if (window.localStorage) {
window.localStorage.setItem(key, val);
}
return val;
}
function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}
function timer() {
count = setLocalStorage('count', count - 1);
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
<div id="timer"></div>
You can try it out here: https://jsfiddle.net/rcg4mt9x/
i want this my javascript code to to be able to be reading 3 hours countdown and also redirect to a new page after the countdown is complete
<script type="text/javascript">
// properties
var count = 0;
var counter = null;
window.onload = function() {
initCounter();
};
function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}
function setLocalStorage(key, val) {
if (window.localStorage) {
window.localStorage.setItem(key, val);
}
return val;
}
function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}
function timer() {
count = setLocalStorage('count', count - 1);
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
<div id="timer"></div>
please help me make it better by making it been able to countdown to three hour and also redirect to another page after the countdown is complete
You didn't properly set total time. You set it to 16 minutes instead of 3 hours. Here is the working code (try it on JSFiddle):
var time = 60 * 60 * 3;
var div = document.getElementById("timer");
var t = Date.now();
var loop = function(){
var dt = (Date.now() - t) * 1e-3;
if(dt > time){
doWhateverHere();
}else{
dt = time - dt;
div.innerHTML = `Hours: ${dt / 3600 | 0}, Minutes: ${dt / 60 % 60 | 0}, Seconds: ${dt % 60 | 0}`;
}
requestAnimationFrame(loop);
};
loop();
Also, do not use setInterval and setTimeout for precise timing. These functions are volatile. Use Date.now() instead.
I have developed a JavaScript countdown timer; also I have a SharePoint list that retrieves the minutes for countdown and its column name is Koha
I am retrieving Koha and initializing in a variable; But when I try running the app the countdown timer shows me NaN?
This is how I am retrieving Koha field:
function Retrieve(){
currentQuizItem = quizList.getItemById(quizID);
var quizName;
context.load(currentQuizItem);
var koha = currentQuizItem.get_fieldValues()["koha"];
//even if I try to convert it to number it does not work
koha = parseInt(Koha);
alert(koha); // here I can see my value but later when I initialize this var to countdown it says NaN;
}
This is my JavaScript countdown timer
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveSec = 60 * koha, //If I make this 60 * 20 it works and there are 20 min to countdown
display = document.querySelector('#UItimer');
startTimer(fiveSec, display);
};
Now when I run my app if shown me NaN:NaN instead of showing me timer
please help me
Most likely you are getting this error since the SP.ClientContext.executeQueryAsync method is missing. The specified method is mandatory, it submits the pending query on the server, without it the line
var koha = currentQuizItem.get_fieldValues()["koha"];
returns undefined.
Here is a generic example for getting list item
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var item = list.getItemById(itemId);
ctx.load(item);
ctx.executeQueryAsync(
function(){
var val = item.get_fieldValues()[fieldName];
//...
},
function(sender,args){
console.log(args.get_message());
});
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>