How To Increase Countdown With Input Well Running? - javascript

I want to restart the setInterval for only -1 second every time I click insert any idea? how to make it restart and increase my value well running? For example clear the setInterval -1 second session from tick( ) and start a new -1 second session so the tick() wont keep looping the function every time I click it
var timeInSecs;
var ticker;
function startTimer() {
var newValues = document.getElementById("mm").value;
var secondInput = document.getElementById("secondsdown").value;
if (secondInput == null || secondInput == '') {
secondInput = '0';
} else {
secondInput = document.getElementById("secondsdown").value;
}
var secs = 60 * parseInt(newValues);
timeInSecs = parseInt(secs + parseInt(secondInput));
ticker = setInterval("tick()", 1000);
}
function tick() {
var secs = timeInSecs;
document.getElementById("secondsdown").value = secs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker);
}
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 pretty = ((hours < 10) ? "0" : "") + hours + ":" + ((mins < 10) ? "0" : "") + mins + ":" + ((secs < 10) ? "0" : "") + secs;
document.getElementById("countdown").innerHTML = pretty;
}
<div class="master-slider ms-skin-light-2" id="masterslider">
<div class="ms-slide">
<input type="number" id="secondsdown"/>
<span id="countdown"></span>
<input id="mm" placeholder="分钟" type="number";/>
<input type="button" value="Click" onclick="startTimer()"/>
</div>
</div><!-- end of masterslider1 -->
I understand this line cause the issues but how to stop it increase from i++
ticker = setInterval(tick, 1000);

I guess it depends on how you look at it :) You've started alright, but the problem is your startTimer(), where upon every click, you always start a new interval.
This shouldn't really be necessary, so either:
always clear the interval before starting a new interval
only start the interval if no interval was active yet
As I'm not sure what your goal is, the easiest change was to consecutively call clearInterval and setInterval.
The only other thing I've changed, is to call tick() once inside the startTimer so that the user doesn't have to wait 1 second before a reaction comes from the UI ( which is a bit confusing :) )
var timeInSecs;
var ticker;
function startTimer() {
var newValues = document.getElementById("mm").value;
var secondInput = document.getElementById("secondsdown").value;
if (secondInput == null || secondInput == '') {
secondInput = '0';
} else {
secondInput = document.getElementById("secondsdown").value;
}
var secs = 60 * parseInt(newValues);
timeInSecs = parseInt(secs + parseInt(secondInput));
tick();
// clear any previous timers
clearInterval( ticker );
// start new timer
ticker = setInterval(tick, 1000);
}
function tick() {
var secs = timeInSecs;
document.getElementById("secondsdown").value = secs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker);
}
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 pretty = ((hours < 10) ? "0" : "") + hours + ":" + ((mins < 10) ? "0" : "") + mins + ":" + ((secs < 10) ? "0" : "") + secs;
document.getElementById("countdown").innerHTML = pretty;
}
<div class="master-slider ms-skin-light-2" id="masterslider">
<div class="ms-slide">
<input type="number" id="secondsdown"/>
<span id="countdown"></span>
<input id="mm" placeholder="分钟" type="number";/>
<input type="button" value="Click" onclick="startTimer()"/>
</div>
</div><!-- end of masterslider1 -->

Related

.blur() causes my stopwatch to lag pretty significantly

Hi I have a stopwatch here that works pretty great except that I wanted to add .blur() method to the buttons so that when I click them, the space bar doesn't re-trigger a button when it is pressed.
I got this idea from a bpm counter I was making that integrated the stopwatch and where the space bar thing was a much bigger issue.
I'm just curious, why does simply adding .blur() to my event listener cause the stopwatch to noticeably lag when hitting start/stop? Is there a better alternative I could be using instead? Will this method negatively affect my bpm counter as well? Am I using .blur() correctly?
This is my first post on Stack Overflow so please let me know if I formatted this question wrong in any way.
// initialize variables
const STARTSTOP = document.querySelector('.start-stop');
const RESET = document.querySelector('.reset');
const STOPWATCH = document.querySelector('.stopwatch');
const DISPLAY = document.querySelector('.display');
let stopwatchIsActive = false;
let elapsedTime = 0;
var myInterval;
// stopwatch functions
function convertElapsedTimeToString() {
let milliseconds = Math.floor((elapsedTime % 1000) / 10),
seconds = Math.floor((elapsedTime / 1000) % 60),
minutes = Math.floor((elapsedTime / (1000 * 60)) % 60),
hours = Math.floor((elapsedTime / (1000 * 60 * 60)) % 24);
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
milliseconds = (milliseconds < 10) ? "0" + milliseconds : milliseconds;
STOPWATCH.innerHTML = minutes + ":" + seconds + ":" + milliseconds;
if (hours >= 1) {
hours = (hours < 10) ? "0" + hours : hours;
STOPWATCH.innerHTML = hours + ":" + minutes + ":" + seconds;
};
}
function resetStopwatch() {
STOPWATCH.innerHTML = "00:00:00";
stopwatchIsActive = false;
elapsedTime = 0;
clearInterval(myInterval);
};
function startStopStopwatch() {
if (stopwatchIsActive) {
clearInterval(myInterval);
convertElapsedTimeToString();
stopwatchIsActive = false;
} else if (elapsedTime > 0) {
startTime = Date.now() - elapsedTime;
clearInterval(myInterval);
myInterval = setInterval(function() {
elapsedTime = Date.now() - startTime;
convertElapsedTimeToString();
}, 10);
stopwatchIsActive = true;
} else {
startTime = Date.now();
myInterval = setInterval(function() {
elapsedTime = Date.now() - startTime;
convertElapsedTimeToString();
}, 10);
stopwatchIsActive = true;
}
};
// executes stopwatch functions
RESET.addEventListener("click", () => {
resetStopwatch();
RESET.blur();
});
STARTSTOP.addEventListener("click", () => {
startStopStopwatch();
STARTSTOP.blur();
});
DISPLAY.addEventListener("click", () => {
startStopStopwatch();
});
<div class="container">
<header class="header">This is a Stopwatch.</header>
<div class="display">
<h2 class="stopwatch">00:00:00</h2>
</div>
<div class="stats">
<button class="start-stop">Start/Stop</button>
</div>
<button class="reset">RESET</button>
</div>

Trying to stop counting clicks after timer is finished

I'm trying to get my button to stop counting clicks after a 10 second count down timer has finished but I don't know how to stop it properly.
When I try to use:
if (seconds < 1)
Then it just comes up with this error in the console:
Uncaught ReferenceError:
seconds is not defined
at onClick ((index):60)
at HTMLButtonElement.onclick ((index):18)
onClick # (index):60
onclick # (index):18
Can someone help me with this?
Here is my code so far:
<body>
<p align="center">
<button class="button" style="width:500px;height:200px;" id="submit2" onClick="onClick()" align="center">Click me!</button>
</p>
<div id="countdowntimertxt" class="countdowntimer" align="center">00:00</div>
<script type="text/javascript">
var sTime = new Date().getTime();
var countDown = 10; // Number of seconds to count down from.
function UpdateCountDownTime() {
var cTime = new Date().getTime();
var diff = cTime - sTime;
var timeStr = '';
var seconds = countDown - Math.floor(diff / 1000);
if (seconds >= 0) {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor( (seconds-(hours*3600)) / 60);
seconds -= (hours*3600) + (minutes*60);
if( hours < 10 ){
timeStr = "" + hours;
}
if( minutes < 10 ){
timeStr = timeStr + ":0" + minutes;
}else{
timeStr = timeStr + ":" + minutes;
}
if( seconds < 10){
timeStr = timeStr + ":0" + seconds;
}else{
timeStr = timeStr + ":" + seconds;
}
document.getElementById("countdowntimertxt").innerHTML = timeStr;
}else{
document.getElementById("countdowntimertxt").style.display="none";
clearInterval(counter);
}
}
UpdateCountDownTime();
var counter = setInterval(UpdateCountDownTime, 500);
var clicks = 0;
function onClick() {
if (seconds < 1) {
clearInterval(clicks)
}else{
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
};
</script>
<p align="center">Clicks: <a id="clicks">0</a></p>
</p>
</body>
You define seconds inside of UpdateCountDownTime() but also access it in onClick. The value in onClick (since we are running in non-strict mode) will be on the global scope and be undefined. Since undefined < 1 will always evaluate to false, then the interval will never be cleared from a click.
You might try adding a var seconds outside of UpdateCountDownTime and then update that, i.e.
var sTime = new Date().getTime();
var countDown = 10; // Number of seconds to count down from.
var seconds = 10; // Number of remaining seconds
function UpdateCountDownTime() {
var cTime = new Date().getTime();
var diff = cTime - sTime;
var timeStr = '';
seconds = countDown - Math.floor(diff / 1000);
var sTime = new Date().getTime();
var countDown = 10; // Number of seconds to count down from.
var seconds;
function UpdateCountDownTime() {
var cTime = new Date().getTime();
var diff = cTime - sTime;
var timeStr = '';
seconds = countDown - Math.floor(diff / 1000);
if (seconds >= 0) {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor( (seconds-(hours*3600)) / 60);
seconds -= (hours*3600) + (minutes*60);
if( hours < 10 ){
timeStr = "" + hours;
}
if( minutes < 10 ){
timeStr = timeStr + ":0" + minutes;
}else{
timeStr = timeStr + ":" + minutes;
}
if( seconds < 10){
timeStr = timeStr + ":0" + seconds;
}else{
timeStr = timeStr + ":" + seconds;
}
document.getElementById("countdowntimertxt").innerHTML = timeStr;
}else{
document.getElementById("countdowntimertxt").style.display="none";
clearInterval(counter);
}
}
UpdateCountDownTime();
var counter = setInterval(UpdateCountDownTime, 500);
var clicks = 0;
function onClick() {
if (seconds < 1) {
clearInterval(clicks)
}else{
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
};
<p align="center">
<button class="button" style="width:500px;height:200px;" id="submit2" onClick="onClick()" align="center">Click me!</button>
</p>
<div id="countdowntimertxt" class="countdowntimer" align="center">00:00</div>
<p align="center">Clicks: <a id="clicks">0</a></p>
</p>
var seconds should be Global variable.

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

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;
}

Backcountdown Timer creation in the alertbox

I have an requirement to create a timer in that will show up in the alertbox of javascript and it will start counting back from 4 minutes to 0.. The moment time is over , it should stop the timer. Everything I want this to be created in Javascript. I have tried with following code that I got from this link:
Timer in Javascript
But it is not working with me. I have done this::
<script>
window.onload = CreateTimer("timer", 30);
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if (TotalSeconds <= 0) {
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : +Time;
}
</script>
<div class="page">
<div id='timer' style="float: left; width: 50%; background-color: red; color: white;"></div>
</div>
I hope, it will help you.
window.onload = CreateTimer("timer", 30);
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout(Tick, 1000); // remove double quote
}
function Tick() {
if (TotalSeconds <= 0) {
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout(Tick, 1000); // remove double quote
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : +Time;
}
Comments are there where I had done changes. Also you need to modify your code as per requirement as alert message is display after every moment when seconds equal to 0 whether time is remaining. I didn't know your requirement about this I didn't touch that code.
Please follow this link for live demo.

Javascript countdown script from fixed postion

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.

Categories

Resources