I'm trying to make a JavaScript countdown clock that starts from 1 hour all the way down.
I'm using just a bit of jQuery in the process.
$(document).ready(function(){
var h,m,s,output;
$("#StartW").click(function(){
function startWork()
{
h = 1;
m = 0;
s = 0;
output = h + ":" + m + ":" + s;
setInterval(function() {count()}, 1000);
}
function count()
{
if(s == 0)
{
if(m == 0)
{
if(h == 0);
{
output = "time's up";
}
h = 0;
m = 59;
s = 59;
}
m = m - 1;
s = 59;
}
s = s - 1;
output = h + ":" + m + ":" + s;
document.getElementById("WTM").innerHTML = output;
}
});
});
1- StartW is the id of the button calling the function.
2- WMT is the id of the span where the clock will be displayed.
When I click the button, I get no results. Nothing happens. The JavaScript Console in my navigator doesn't indicate any errors at all.
Actually, at pressing that button you don't call any function, you just initiate them. Get outside from click event the functions count and startWork, and do stuff like
$('#StartW').on( 'click', startWork );
Check it here
In your click event function, you declare two functions, but never call them, so nothing happens. Try this:
$(document).ready(function(){
var h,m,s,output;
$("#StartW").click(function(){
function startWork()
{
h = 1;
m = 0;
s = 0;
output = h + ":" + m + ":" + s;
setInterval(function() {count()}, 1000);
}
function count()
{
if(s == 0)
{
if(m == 0)
{
if(h == 0)
{
output = "time's up";
}
h = 0;
m = 59;
s = 59;
}
m = m - 1;
s = 59;
}
s = s - 1;
output = h + ":" + m + ":" + s;
document.getElementById("WTM").innerHTML = output;
}
startWork();
});
});
Fixing indentation made it super clear, also there is a ; on the line if(h == 0); that should be removed
As a note for your way to count one hour, you need to understand that it might not be very accurate. You ask the code to wait for 1000 milliseconds to add 1 second yourself, exactly like we do to count seconds saying "mississipi" to help us wait for the next second. Although JavaScript is more precise at counting 1000Milliseconds in 1 sec as we are to say mississipi in exactly one second, it might be off for X and Y reasons. The only real accurate way to know how long has elapsed is to watch the clock, and look at it again and again until it shows that we waited an hour. So, in JS, save the time when it started, every second or so display the remaining time by the difference of the current time and started time and display the timer.
Related
I have a web page where I entered a countdown code and it works well. However, I can only call it 1 time with the id in html.
Second or third time, it no longer works. How can I always use it? I would need it 3 or 4 times on the page. Thank you.
This is the code:
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 + " ore " + minutes + " min " + seconds + " sec"; // watch for spelling
}
You need to encapsulate the functionality in a way that can be called many times. It usually helps to think about the question "As a programmer, how I'd like to use this?"
Usually, it's a single function that takes some parameters and does something and/or returns something.
As an example... wouldn't it be nice if we had a function startMyTimer(...) that takes a timerId, and an element and sets up a timer that will update that element? We already have the signature:
function startMyTimer(timerId, element) { ... }
And now you can build everything inside this function. JS allows declaring functions within functions, which helps with encapsulation, so copying from your code it would look like:
function startMyTimer(timerId, element) {
var count = getLocalStorage(timerId) || 1000;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = setLocalStorage(timerId, 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;
element.innerHTML = hours + " ore " + minutes + " min " + seconds + " sec"; // watch for spelling
}
}
Note that now count and counter are both private to the scope of startMyTimer, so only within this function (and any function inside this one, such as function timer()) will see these variables.
So if you want to do exactly what you did, you'd use this function as
window.onload = function() {
startMyTimer('count', document.getElementById("timer"));
};
Again, this is just an example of a posible solution - Maybe you could pass in the element id instead of the element, or a timer duration, etc., and the best solution is the one that fits best your needs.
I want to create a countdown timer which looks like an fps counter for webpage...
after hours of time spent i m not able to find out what is wrong.....help
<script>
var myvar = setInterval(function () { startTimer() }, 1000);
function startTimer() {
var presentTime = 17 + ":" + 00;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if (s == 59) {
m = m - 1
}
//if(m<0){alert('timer completed')}
var button2 = document.createElement("Button2");
var interval = m + s;
button2.innerHTML = Math.round(interval);
button2.style = "top:0; left:0rem; height:10% ;color: black; background-color: #ffffff;position:fixed;padding:20px;font-size:large;font-weight: bold;";
setTimeout(startTimer, 1000);
document.body.appendChild(button2);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec
}; // add zero in front of numbers < 10
if (sec < 0) {
sec = "59"
};
return sec;
}
</script>
I can find three errors that hinder your code from performing correctly.
Multiple timers
First off since you invoke both a setInterval in outer scope, and then a setTimeout after each performed iteration, you will end up getting many unwanted timer instances that will do some crazy counting for you.
I recommend you to scrap either one of these and stick with just one of them.
For my example i happend to stick with the setInterval since you're executing the very same method over and over any way.
The initialization
Since the presentTime is declared inside the startTimer-function it will be constantly overwritten with 17 + ":" + 00 (resulting in "17:0" btw).
This is solved by declaring it in the outer scope instead.
Remembering the changes
Finally you need to save the current state of presentTime after modifications. Just adding a presentTime = [m,s].join(":"); at the end of startTimer() solves this.
var presentTime = "17:00";
function startTimer() {
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if (s == 59) {
m = m - 1
}
var button2 = document.createElement("Button2");
var interval = s;
button2.innerHTML = m + ":" + s;
button2.style = "top:0; left:0rem; height:10% ;color: black; background-color: #ffffff;position:fixed;padding:20px;font-size:large;font-weight: bold;";
document.body.appendChild(button2);
presentTime = [m,s].join(":");
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec
}; // add zero in front of numbers < 10
if (sec < 0) {
sec = "59"
};
return sec;
}
var interval = setInterval(startTimer, 1000);
I know this isn't going to help you understand so I'll break it down.
I have a webpage that has an interval for the time, this time is translated into an hour and that loads a audio file. The problem being that the interval reloads the audio every second and I only want it to interval based on the hour and the clock to work as intended. I have it set up like this.
The basic of it is that I have a page loading stuff based on the time of day and I need a way to edit the time live with some function and change the elements. If there is a better way to do this, I am open to suggestions.
note: i can not use jquery
//interval//
var myVar = setInterval(function(){ myTimer() }, 1000);
//get the time//
function myTimer() {
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var time = h + ":" + m + ":" + s;
document.getElementById('time').innerHTML = time;
mod_time(h,m,s)
}
// mod the time //
function mod_time(h,m,s) {
var x = 0;
if(x == 1){
var h = h - h + 2
}
if(x == 2){
var h = h - h + 3
}
else{
var h = h;
}
//applying just the hours//
apply_mod_time(h)
//displaying the full modded time for debugging//
var t_str = h + ":" + m + ":" + s;
document.getElementById('time2').innerHTML = t_str;
}
//playing sound based on the hour//
function apply_mod_time(h) {
if (h==1) {
document.getElementById("myAudio").src = "moo.mp3";
}
}
Add another variable that specifies the current hour. When you execute the interval every second, see if h !== hourVariable. If they do not match, load the audio file and update the hourVariable to equal h.
I am using timer in my project , I am having two problems in it. When start button is press time should start & when end button is press time should end.
But 1)when end button is clicked
time is not stopping .
2)when time decrease & reach 1 minute..time is stopped ..it should reduse in seconds also
var tim;
var min = 10;
var sec = 10;
var f = new Date();
function f1() {
f2();
document.getElementById("starttime").innerHTML = "Your started your Exam at " + f.getHours() + ":" + f.getMinutes();
}
function f2() {
if (parseInt(sec) > 0) {
sec = parseInt(sec) - 1;
document.getElementById("showtime").innerHTML = "Your Left Time is :" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
} else {
if (parseInt(sec) == 0) {
min = parseInt(min) - 1;
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = ".././Home/Login";
} else {
sec = 60;
document.getElementById("showtime").innerHTML = "Your Left Time is :" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
}
}
}
}
My suggestion would be this:
Fiddle
var tim;
var sec;
var f = new Date();
function f1() {
sec = 10 * 60;
f2();
document.getElementById("starttime").innerHTML = "Your started your Exam at " + f.getHours() + ":" + f.getMinutes();
}
function f2() {
if (sec > 0) {
sec--;
tim = setTimeout(f2, 1000);
} else {
document.getElementById("starttime").innerHTML = "times up!!!!";
}
var min = Math.floor(sec / 60);
var secDisplay = sec % 60;
document.getElementById("showtime").innerHTML = "Your Left Time is : " + min + " Minutes," + secDisplay + " Seconds";
}
function end() {
clearTimeout(tim);
sec = 0;
f2();
}
Changes are:
Removed the min variable and only use the total seconds instead of two variables. We can easily calculate the minutes based on the total seconds, for the display purposes. Using the seconds variable makes it much easier to check the time remaining. As you can see the code is simplified a lot.
Changed the setTimeout to take the function as an argument, not a string.
Added end() function, to be called when the end button is clicked.
Moved the seconds count to inside f1() so that it can be started and ended repeatedly without reloading the page.
Removed unnecessary parseInt() calls. The sec variable is already of numerical type so no need to convert it.
The timer will stop when the seconds reduce to 0. If you want it to stop when the time remaining reaches one minute, just change the condition in f2() to if (sec > 60) {
For your first question about the end button i cannot see any end button functionality. but you could have a stop function that clears the timeout.
function f3() {
clearTimeout(tim);
//update any text you wish here or move to the next page..
}
For your second question why it ends at 1 minute. You are decreasing the minute value before you check if it is zero. So when you come to f2, sec is 0 and min is 1 you then decrease min to 0.. And then check if it is zero and end the execution.
To solve that move your "min = parseInt(min) - 1;" to after the else and it should count the last minute too.
PS. you don't need parseint since you are using numbers allready
I try it with javascript and jquery but no idea how to do that. i wont to let the timer not begins on refreshing counting again. It´s same as an auction when he counting down 3,2 and on refreshing he don´t begins again it should continue count down where it last ended. And on other products it must count from 3 again. Have anyboy an idea?
Edit: because some users missunderstood what i am searching for.
my issue is that i don´t know how to save the time when someone refresh the page to continue to count it down. if someone refresh the site at 21sec and he or she have 30 secs to make there choice. and after refreshing the site, the counter will count at 21sec down and not started again by 30sec again.
no ajax.
When possible hardcoded.
And if not possible then the cookie variant.
You can set a name to your window on load of the page. Before setting the name check whether this window already has a name.
if it doesn't have a name, set a name to the window and start counting at 0 and save the count value in a cookie each time it increment.
if it does have a name(that means page is reloaded), read the count value from the cookie and do the increment and save to cookie.
EDIT: Example, Call initCount() function on body load. Use decrementAndSave function to decrement the value of the count and save it to cookie.
var count = 3;// 3 -> 2 -> 1
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function initCount() {
if (window.name) {
count = getCookie("count_" + window.name);// to keep separate count cookies for each window
} else {
window.name = "w_" + (new Date().getTime());
count = 3;
setCookie("count_" + window.name, count, null);
}
}
function decrementAndSave() {
count--;
// separate cookie for each window or tab
setCookie("count_" + window.name, count, null);
}
It's not Perfect but I designed this script to do a 30min countdown and then to change some text during the last few seconds. The only issue with it is that when it gets to 1:00 it starts at 30:60 and I haven't figured out how to fix that yet. This may not work perfectly for what your looking for but it might put you on the right path.
<script>
//add leading zeros
setInterval(function() {
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var x = document.getElementById("timer");
var d = new Date();
var s = (d.getSeconds());
var m = (d.getMinutes());
var a = addZero(30 - m);
var b = addZero(60 - m);
var c = (60 - s);
var z = "<span style='color:red;font-size:50px;'>" + "Break" + "</span>";
var v = "<span style='color:black;font-size:24px;'>" + "Break" + "</span>";
//Decide how much should be subtracted from the time
if (m > 30) {
y = b;
}
else if (m < 30) {
y = a;
}
//elements for changing text
if (y < 2 && c < 15) {
q = z;
}
else {
q = v;
}
var t = y + (":" + addZero(c) + " Till Station " + (q));
x.innerHTML = t;
}, 250);
</script>
<div align="center" id="timer" style='color:black;font-size:24px;' ></div>
If you have a countdown, then you must have some sort of end time defined. So instead of having a countdown and just subtracting 1 every second, try something like this:
var endTime = new Date(2011,11,13,0,0,0); // Midnight of December 13th 2011
var timer = setInterval(function() {
var now = new Date();
var timeleft = Math.max(0,Math.floor((endTime.getTime()-now.getTime())/1000));
var d, h, m, s;
s = timeleft % 60;
timeleft = Math.floor(timeleft/60);
m = timeleft % 60;
timeleft = Math.floor(timeleft/60);
h = timeleft % 24;
timeleft = Math.floor(timeleft/24);
d = timeleft;
document.getElementById('counter').innerHTML = "Time left: "+d+" days, "+h+" hours, "+m+" minutes, "+s+" seconds.";
if( timeleft == 0) clearInterval(timer);
},1000);
var interval = 90000; //90 secounds
function reset() {
localStorage.endTime = +new Date() + interval;
}
if (!localStorage.endTime) {
reset();
}
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}
setInterval(function () {
var remaining = localStorage.endTime - new Date();
if (remaining >= 0) {
document.getElementById("tooltip").innerText =
millisToMinutesAndSeconds(remaining);
} else {
reset();
}
}, 100);