Countup since a specific date in javascript/jQuery [duplicate] - javascript

I want to use a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. No milliseconds. How can it be coded?

var count=30;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
//counter ended, do something here
return;
}
//Do code for showing the number of seconds here
}
To make the code for the timer appear in a paragraph (or anywhere else on the page), just put the line:
<span id="timer"></span>
where you want the seconds to appear. Then insert the following line in your timer() function, so it looks like this:
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}

I wrote this script some time ago:
Usage:
var myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
myCounter.start();
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}

So far the answers seem to rely on code being run instantly. If you set a timer for 1000ms, it will actually be around 1008 instead.
Here is how you should do it:
function timer(time,update,complete) {
var start = new Date().getTime();
var interval = setInterval(function() {
var now = time-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
}
else update(Math.floor(now/1000));
},100); // the smaller this number, the more accurate the timer will be
}
To use, call:
timer(
5000, // milliseconds
function(timeleft) { // called every step to update the visible countdown
document.getElementById('timer').innerHTML = timeleft+" second(s)";
},
function() { // what to do after
alert("Timer complete!");
}
);

Here is another one if anyone needs one for minutes and seconds:
var mins = 10; //Set the number of minutes you need
var secs = mins * 60;
var currentSeconds = 0;
var currentMinutes = 0;
/*
* The following line has been commented out due to a suggestion left in the comments. The line below it has not been tested.
* setTimeout('Decrement()',1000);
*/
setTimeout(Decrement,1000);
function Decrement() {
currentMinutes = Math.floor(secs / 60);
currentSeconds = secs % 60;
if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
document.getElementById("timerText").innerHTML = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
if(secs !== -1) setTimeout('Decrement()',1000);
}

// Javascript Countdown
// Version 1.01 6/7/07 (1/20/2000)
// by TDavid at http://www.tdscripts.com/
var now = new Date();
var theevent = new Date("Sep 29 2007 00:00:01");
var seconds = (theevent - now) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
ID = window.setTimeout("update();", 1000);
function update() {
now = new Date();
seconds = (theevent - now) / 1000;
seconds = Math.round(seconds);
minutes = seconds / 60;
minutes = Math.round(minutes);
hours = minutes / 60;
hours = Math.round(hours);
days = hours / 24;
days = Math.round(days);
document.form1.days.value = days;
document.form1.hours.value = hours;
document.form1.minutes.value = minutes;
document.form1.seconds.value = seconds;
ID = window.setTimeout("update();", 1000);
}
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>
</p>
<form name="form1">
<p>Days
<input type="text" name="days" value="0" size="3">Hours
<input type="text" name="hours" value="0" size="4">Minutes
<input type="text" name="minutes" value="0" size="7">Seconds
<input type="text" name="seconds" value="0" size="7">
</p>
</form>

Just modified #ClickUpvote's answer:
You can use IIFE (Immediately Invoked Function Expression) and recursion to make it a little bit more easier:
var i = 5; //set the countdown
(function timer(){
if (--i < 0) return;
setTimeout(function(){
console.log(i + ' secs'); //do stuff here
timer();
}, 1000);
})();
var i = 5;
(function timer(){
if (--i < 0) return;
setTimeout(function(){
document.getElementsByTagName('h1')[0].innerHTML = i + ' secs';
timer();
}, 1000);
})();
<h1>5 secs</h1>

Expanding upon the accepted answer, your machine going to sleep, etc. may delay the timer from working. You can get a true time, at the cost of a little processing. This will give a true time left.
<span id="timer"></span>
<script>
var now = new Date();
var timeup = now.setSeconds(now.getSeconds() + 30);
//var timeup = now.setHours(now.getHours() + 1);
var counter = setInterval(timer, 1000);
function timer() {
now = new Date();
count = Math.round((timeup - now)/1000);
if (now > timeup) {
window.location = "/logout"; //or somethin'
clearInterval(counter);
return;
}
var seconds = Math.floor((count%60));
var minutes = Math.floor((count/60) % 60);
document.getElementById("timer").innerHTML = minutes + ":" + seconds;
}
</script>

For the sake of performances, we can now safely use requestAnimationFrame for fast looping, instead of setInterval/setTimeout.
When using setInterval/setTimeout, if a loop task is taking more time than the interval, the browser will simply extend the interval loop, to continue the full rendering. This is creating issues. After minutes of setInterval/setTimeout overload, this can freeze the tab, the browser or the whole computer.
Internet devices have a wide range of performances, so it's quite impossible to hardcode a fixed interval time in milliseconds!
Using the Date object, to compare the start Date Epoch and the current. This is way faster than everything else, the browser will take care of everything, at a steady 60FPS (1000 / 60 = 16.66ms by frame) -a quarter of an eye blink- and if the task in the loop is requiring more than that, the browser will drop some repaints.
This allow a margin before our eyes are noticing (Human = 24FPS => 1000 / 24 = 41.66ms by frame = fluid animation!)
https://caniuse.com/#search=requestAnimationFrame
/* Seconds to (STRING)HH:MM:SS.MS ------------------------*/
/* This time format is compatible with FFMPEG ------------*/
function secToTimer(sec){
const o = new Date(0), p = new Date(sec * 1000)
return new Date(p.getTime()-o.getTime()).toString().split(" ")[4] + "." + p.getMilliseconds()
}
/* Countdown loop ----------------------------------------*/
let job, origin = new Date().getTime()
const timer = () => {
job = requestAnimationFrame(timer)
OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000)
}
/* Start looping -----------------------------------------*/
requestAnimationFrame(timer)
/* Stop looping ------------------------------------------*/
// cancelAnimationFrame(job)
/* Reset the start date ----------------------------------*/
// origin = new Date().getTime()
span {font-size:4rem}
<span id="OUT"></span>
<br>
<button onclick="origin = new Date().getTime()">RESET</button>
<button onclick="requestAnimationFrame(timer)">RESTART</button>
<button onclick="cancelAnimationFrame(job)">STOP</button>

You can do as follows with pure JS. You just need to provide the function with the number of seconds and it will do the rest.
var insertZero = n => n < 10 ? "0"+n : ""+n,
displayTime = n => n ? time.textContent = insertZero(~~(n/3600)%3600) + ":" +
insertZero(~~(n/60)%60) + ":" +
insertZero(n%60)
: time.textContent = "IGNITION..!",
countDownFrom = n => (displayTime(n), setTimeout(_ => n ? sid = countDownFrom(--n)
: displayTime(n), 1000)),
sid;
countDownFrom(3610);
setTimeout(_ => clearTimeout(sid),20005);
<div id="time"></div>

Based on the solution presented by #Layton Everson I developed a counter including hours, minutes and seconds:
var initialSecs = 86400;
var currentSecs = initialSecs;
setTimeout(decrement,1000);
function decrement() {
var displayedSecs = currentSecs % 60;
var displayedMin = Math.floor(currentSecs / 60) % 60;
var displayedHrs = Math.floor(currentSecs / 60 /60);
if(displayedMin <= 9) displayedMin = "0" + displayedMin;
if(displayedSecs <= 9) displayedSecs = "0" + displayedSecs;
currentSecs--;
document.getElementById("timerText").innerHTML = displayedHrs + ":" + displayedMin + ":" + displayedSecs;
if(currentSecs !== -1) setTimeout(decrement,1000);
}

// Javascript Countdown
// Version 1.01 6/7/07 (1/20/2000)
// by TDavid at http://www.tdscripts.com/
var now = new Date();
var theevent = new Date("Nov 13 2017 22:05:01");
var seconds = (theevent - now) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
ID = window.setTimeout("update();", 1000);
function update() {
now = new Date();
seconds = (theevent - now) / 1000;
seconds = Math.round(seconds);
minutes = seconds / 60;
minutes = Math.round(minutes);
hours = minutes / 60;
hours = Math.round(hours);
days = hours / 24;
days = Math.round(days);
document.form1.days.value = days;
document.form1.hours.value = hours;
document.form1.minutes.value = minutes;
document.form1.seconds.value = seconds;
ID = window.setTimeout("update();", 1000);
}
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>
</p>
<form name="form1">
<p>Days
<input type="text" name="days" value="0" size="3">Hours
<input type="text" name="hours" value="0" size="4">Minutes
<input type="text" name="minutes" value="0" size="7">Seconds
<input type="text" name="seconds" value="0" size="7">
</p>
</form>

My solution works with MySQL date time formats and provides a callback function. on complition.
Disclaimer: works only with minutes and seconds, as this is what I needed.
jQuery.fn.countDownTimer = function(futureDate, callback){
if(!futureDate){
throw 'Invalid date!';
}
var currentTs = +new Date();
var futureDateTs = +new Date(futureDate);
if(futureDateTs <= currentTs){
throw 'Invalid date!';
}
var diff = Math.round((futureDateTs - currentTs) / 1000);
var that = this;
(function countdownLoop(){
// Get hours/minutes from timestamp
var m = Math.floor(diff % 3600 / 60);
var s = Math.floor(diff % 3600 % 60);
var text = zeroPad(m, 2) + ':' + zeroPad(s, 2);
$(that).text(text);
if(diff <= 0){
typeof callback === 'function' ? callback.call(that) : void(0);
return;
}
diff--;
setTimeout(countdownLoop, 1000);
})();
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
}
// $('.heading').countDownTimer('2018-04-02 16:00:59', function(){ // on complete})

var hr = 0;
var min = 0;
var sec = 0;
var count = 0;
var flag = false;
function start(){
flag = true;
stopwatch();
}
function stop(){
flag = false;
}
function reset(){
flag = false;
hr = 0;
min = 0;
sec = 0;
count = 0;
document.getElementById("hr").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("count").innerHTML = "00";
}
function stopwatch(){
if(flag == true){
count = count + 1;
setTimeout( 'stopwatch()', 10);
if(count ==100){
count =0;
sec = sec +1;
}
}
if(sec ==60){
min = min +1 ;
sec = 0;
}
if(min == 60){
hr = hr +1 ;
min = 0;
sec = 0;
}
var hrs = hr;
var mins = min;
var secs = sec;
if(hr<10){
hrs ="0" + hr;
}
if(min<10){
mins ="0" + min;
}
if(sec<10){
secs ="0" + sec;
}
document.getElementById("hr").innerHTML = hrs;
document.getElementById("min").innerHTML = mins;
document.getElementById("sec").innerHTML = secs;
document.getElementById("count").innerHTML = count;
}

Related

Javascript Descending Timer with Minutes, Seconds and Milliseconds

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

Pause/Resume javascript Pomodoro clock

I've been working on a Javascript pomodoro clock. I am able to set the session time and break time and it counts down without any trouble. But for some reason I can not get pause and resume to work. When the timer starts I capture the Date.now() and when I pause it I capture the current Date.now(). I find the difference and subtract from the duration, hoping to resume at the paused time, but it still keeps subtracting additional seconds. My code (from codepen) is below
$(document).ready(function() {
var total;
var i;
var x;
var y;
var display;
var minutes;
var seconds;
var duration;
var sessionInterval;
var freeze;
var timePast;
var t;
var start;
var clock;
function timer(end) {
total = Date.parse(end) - Date.parse(new Date());
minutes = Math.floor((total / 1000 / 60) % 60);
seconds = Math.floor((total / 1000) % 60);
return {
'total': total,
'minutes': minutes,
'seconds': seconds
};
}
function beginTimer() {
start = Date.now();
clearInterval(sessionInterval);
clock = document.getElementById('display2');
start = Date.now();
sessionInterval = setInterval(function() {
t = timer(duration);
clock.innerHTML = 'minutes:' + t.minutes + '<br>' + 'seconds:' + t.seconds + '<br>';
if (t.total <= 0) {
clearInterval(sessionInterval);
if (i === 0) {
session();
} else if (i === 1) {
breakTime();
}
}
}, 1000);
}
function session() {
duration = new Date(Date.parse(new Date()) + (x * 60 * 1000));
beginTimer();
i = 1;
}
function breakTime() {
duration = new Date(Date.parse(new Date()) + (y * 60 * 1000));
beginTimer();
i = 0;
}
$(".sendInput").click(function() {
if (x == null) {
x = 25;
} else {
x = parseInt(document.getElementById("workTime").value, 10);
}
if (y == null) {
y = 5;
} else {
y = parseInt(document.getElementById("breakMin").value, 10);
}
session();
});
$(".sendPause").click(function() {
freeze = Date.now();
timePast = freeze - start;
clearInterval(sessionInterval);
});
$(".sendResume").click(function() {
if (i === 1) {
duration = new Date(((Date.parse(new Date())) + (x * 60 * 1000)) - timePast);
}
if (i === 0) {
duration = new Date(((Date.parse(new Date())) + (y * 60 * 1000)) + timePast);
}
beginTimer();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="break: 5 minutes" id="breakMin">
<input type ="text" placeholder="session: 25 minutes" id="workTime">
<input type="button" value="Start" class="sendInput">
<input type="button" value="Pause" class="sendPause">
<input type="button" value="Resume" class="sendResume">
<div id="display2">
</div>
The major logic problem is within the resume function which does not reset start to a new notional value that is timePast milliseconds before the present. Using the original start value after a pause of undetermined duration simply does not work.
Date.parse(new Date()) also appeared to be causing problems. Without spending time on debugging it further, all occurrences of Date.parse(new Date()) were simply replaced with Date.now().
So a slightly cleaned up version of the resume function that appears to work:
$(".sendResume").click(function() {
var now = Date.now();
if (i === 1) {
duration = new Date( now + x * 60 * 1000 - timePast);
}
if (i === 0) {
duration = new Date( now + y * 60 * 1000 + timePast);
}
beginTimer();
start = now - timePast; // <-- reset notional start time
});
but please test it further - you may wish to investigate why timePast is added in one calculation of duration and subtracted in the other!

javascript countdown echoing wrong time

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.

JavaScript timer doesn't start after being reset

The timer, start/pause button and reset button all work as expected.
The only bug it seems to have is, when I run the timer and reset it, it
won't start again. Only after I press the Start/Pause button 2 times it will run again.
Live demo: http://codepen.io/Michel85/full/pjjpYY/
Code:
var timerTime;
var time = 1500;
var currentTime;
var flag = 0;
var calculateTime
// Start your Timer
function startTimer(time) {
document.getElementById("btnUp").disabled = true;
document.getElementById("btnDwn").disabled = true;
timerTime = setInterval(function(){
showTimer();
return flag = 1;
}, 1000);
}
// Reset function
function resetTimer(){
clearInterval(timerTime);
document.getElementById('showTime').innerHTML=(calculateTime(1500));
document.getElementById("btnUp").disabled = false;
document.getElementById("btnDwn").disabled = false;
return time=1500;
}
// Pause function
function pauseTimer(){
clearInterval(timerTime);
currentTime = time;
document.getElementById('showTime').innerHTML=(calculateTime(time));
return flag = 0;
}
// Update field with timer information
function showTimer(){
document.getElementById("showTime").innerHTML=(calculateTime(time));
flag = 1;
if(time < 1){
resetTimer();
}
time--;
};
// Toggle function (Pause/Run)
function toggleTimmer(){
if(flag == 1){
pauseTimer();
} else {
startTimer();
}
}
/*
Round-time up or down
*/
// Set timer Up
function timeUp(){
time += 60;
document.getElementById("showTime").innerHTML=(calculateTime(time));
return time;
}
// Set timer Down
function timeDown(){
if(time > 60){
time-=60;
}
document.getElementById("showTime").innerHTML=(calculateTime(time));
return time;
}
/*
Break-time up down
*/
// Set timer Up
function breakUp(){
time += 60;
document.getElementById("showTime").innerHTML=(calculateTime(time));
return time;
}
// Set timer Down
function breakDown(){
if(time > 60){
time-=60;
}
document.getElementById("showTime").innerHTML=(calculateTime(time));
return time;
}
// Calculate the Days, Hours, Minutes, seconds and present them in a digital way.
function calculateTime(totalTime) {
// calculate days
var days = Math.floor(totalTime / 86400);
totalTime = totalTime % 86400
// calculate hours
var hours = Math.floor(totalTime / 3600);
totalTime = totalTime % 3600;
// calculate minutes
var minutes = Math.floor(totalTime / 60);
totalTime = totalTime % 60;
// calculate seconds
var seconds = Math.floor(totalTime);
function convertTime(t) {
return ( t < 10 ? "0" : "" ) + t;
}
// assign the variables
days = convertTime(days);
hours = convertTime(hours);
minutes = convertTime(minutes);
seconds = convertTime(seconds);
// Make sure the "00:" is present if empty.
if(days !== "00"){
var currentTimeString = days + ":" + hours + ":" + minutes + ":" + seconds;
return currentTimeString;
} else if (hours !== "00"){
var currentTimeString = hours + ":" + minutes + ":" + seconds;
return currentTimeString
} else if(minutes !== "0:00"){
var currentTimeString = minutes + ":" + seconds;
return currentTimeString
} else {
var currentTimeString = seconds;
return currentTimeString
}
}
Any help is welcome.
Thanks in advance.
Greets,
Michel
resetTimer needs to set flag to 0. If it leaves it set at 1, then toggleTimer will call pauseTimer rather than startTimer.
BTW, it's better style to use boolean values (true/false) for flags.
Just remove clearInterval(timerTime); in function resetTimer();
function resetTimer() {
//clearInterval(timerTime);
document.getElementById('showTime').innerHTML = (calculateTime(300));
document.getElementById("btnUp").disabled = false;
document.getElementById("btnDwn").disabled = false;
return time = 300;
}

My javascriptcode is working when i put alert.I need to Display time in Counter Format(Seconds decreasing way)

My javascriptcode is working fine when i put alert.I need to Display time in Counter Format(Second decreasing way). Please help me in resolving this issue
<script type="text/javascript">
window.onload = function () {
//alert("request>>>");
var count = 0;
var start_actual_time = document.getElementById("timerStartTime").value;
var end_actual_time = document.getElementById("timerEndTime").value;
start_actual_time = new Date(start_actual_time);
var start_actual_time1 = new Date(start_actual_time.getTime());
start_actual_time1 = new Date(start_actual_time1);
var end_actual_time1 = new Date(end_actual_time);
var hours =end_actual_time1.getHours()- start_actual_time1.getHours();
var minutes = end_actual_time1.getMinutes() - start_actual_time1.getMinutes();
var seconds = end_actual_time1.getSeconds()- start_actual_time1.getSeconds();
seconds = hours * 3600 + minutes * 60 + seconds;
//alert ("seconds >>." +seconds);
timer(seconds);
};
function timer(seconds) {
alert("calling timer");
var s1 = Number(seconds);
var hours = Math.floor(s1 / 3600);
var minutes = Math.floor(s1 % 3600 / 60);
var s = Math.floor(s1 % 3600 % 60);
//alert("sec1" + s);
display = document.querySelector('#time');
var formatted = ((hours < 10)?("0" + hours):hours) + ":" + ((minutes < 10)?("0" + minutes):minutes) + ":" + ((s < 10)?("0" + s):s)
display.textContent = formatted ;
seconds = seconds - 1;
timer(seconds);
}
</script>
The way your code is written creates a
too much recursion
exception for me.
Therefore I have avoided recursive invokes and used javascript setInterval:
var refreshIntervalId = setInterval(function(){ timer(); }, 1000);
When your seconds reach zero, timer is stopped:
if (seconds == -1){
clearInterval(refreshIntervalId);
Link to working fiddle: http://jsfiddle.net/3ggspruf/2/

Categories

Resources