Why is this JavaScript timer crashing my web page? - javascript

So I'm trying to put together a timer to count down to a specific time on a specific day. I found some code to work with online and adapted it to this
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time)
{
Timer = document.getElementByID(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
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 + " until my birthday!";
}
function LeadingZero(Time)
{
return (Time < 10) ? "0" + Time : + Time;
}
When I start it up on my web page it crashes the page. I know the problem is not how I link it to the HTML because I tested this code on http://writecodeonline.com/javascript/ and it did not work there either. Any advice?

Related

JS CountDown no reload on refresh please

Well my code should be working but it isn't. Each time I reload the time, my Countdown start back at his initialised value.
Since I'm not familliar with JS you may be able to m'éclaircir the mind
<script>
var upgradeTime = 172801;
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;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()',1000,function() {
secondPassed();
if (seconds === 0) {
eraseCookie(seconds);
} else {
createCookie(seconds, seconds, 7);
}
});
</script>
How do I call it
<h1>Server Release in : <span id="countdown" class="timer"></span></h1>
I just want my timer to not refresh each time you reload the page.
Any kind of help would be appreciated
Here you go.
var upgradeTime = 172801; //Timer length in ms
var timerMS = window.localStorage.getItem("date");
startTimer();
function timer() {
var difference = timerMS - Date.now();
if (difference <= 0) {
startTimer();
return;
}
var seconds = (difference / 1000).toFixed(0),
days = Math.floor(seconds / 24 / 60 / 60),
hoursLeft = Math.floor((seconds) - (days * 86400)),
hours = Math.floor(hoursLeft / 3600),
minutesLeft = Math.floor((hoursLeft) - (hours * 3600)),
minutes = Math.floor(minutesLeft / 60),
remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
setTimeout(timer, 1000);
}
function startTimer() {
if (!timerMS || timerMS < Date.now()) {
timerMS = Date.now() + upgradeTime;
window.localStorage.setItem("date", timerMS);
}
timer();
}

Page last updated x time ago in Javascript

Right now I am using livestamp.js and moment.js to show the page updated/refreshed last x time ago. But is it possible to achieve the same in plain js without the use of other js libraries.
var date = new Date();
var finaltime = timeSince(date);
setInterval(function(){
document.getElementsByTagName('span')[0].innerHTML = timeSince(date);
},30000);
document.getElementsByTagName('span')[0].innerHTML = timeSince(date);
function timeSince(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var interval = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + " years";
}
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + " months";
}
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + " days";
}
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + " hours";
}
interval = Math.floor(seconds / 60);
if (interval >= 1) {
return interval + " minutes";
}
return Math.floor(seconds) + " seconds";
}
<div> This page is updated <span> </span> ago.</div>

Countdown Timer Problems

I have been looking for a count down timer on google and can't seem to find one.
I was just wondering if anyone would be able to help.
I got given one but it displays the wrong times.
I want it to display days, hours, minutes and seconds left.
heres what I need the timer on
http://pastebin.com/fQjyRFXw
It already has the timer code there but it's all wrong, any help would be great, thank you
If it's helps here's a snippet of the Java code
var count = <?= $time['a_time'] ?>;
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("clock").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left";
}
Ok I see your problem. The a_time stored in database is an Unix timestamp, thus when you are counting down, you need to know how long is between now and a_time instead of only a_time.
Try this:
var count = <?= $time['a_time'] ?>;
var now = Math.floor(new Date().getTime() / 1000);
count = count - now;
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);
var days = Math.floor(hours / 24);
minutes %= 60;
hours %= 24;
document.getElementById("clock").innerHTML = days + "days " + hours + "hours " + minutes + "minutes and " + seconds + " seconds left";
}
Why not use one of the man examples on codepen such as this beautiful one
http://codepen.io/anon/pen/VeLWdz ?
(function (e) {
e.fn.countdown = function (t, n) {
function i() {
eventDate = Date.parse(r.date) / 1e3;
currentDate = Math.floor(e.now() / 1e3);
if (eventDate <= currentDate) {
n.call(this);
clearInterval(interval)
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / 86400);
seconds -= days * 60 * 60 * 24;
hours = Math.floor(seconds / 3600);
seconds -= hours * 60 * 60;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
days == 1 ? thisEl.find(".timeRefDays").text("day") : thisEl.find(".timeRefDays").text("days");
hours == 1 ? thisEl.find(".timeRefHours").text("hour") : thisEl.find(".timeRefHours").text("hours");
minutes == 1 ? thisEl.find(".timeRefMinutes").text("minute") : thisEl.find(".timeRefMinutes").text("minutes");
seconds == 1 ? thisEl.find(".timeRefSeconds").text("second") : thisEl.find(".timeRefSeconds").text("seconds");
if (r["format"] == "on") {
days = String(days).length >= 2 ? days : "0" + days;
hours = String(hours).length >= 2 ? hours : "0" + hours;
minutes = String(minutes).length >= 2 ? minutes : "0" + minutes;
seconds = String(seconds).length >= 2 ? seconds : "0" + seconds
}
if (!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds)
} else {
alert("Invalid date. Example: 30 Tuesday 2013 15:50:00");
clearInterval(interval)
}
}
var thisEl = e(this);
var r = {
date: null,
format: null
};
t && e.extend(r, t);
i();
interval = setInterval(i, 1e3)
}
})(jQuery);
$(document).ready(function () {
function e() {
var e = new Date;
e.setDate(e.getDate() + 60);
dd = e.getDate();
mm = e.getMonth() + 1;
y = e.getFullYear();
futureFormattedDate = mm + "/" + dd + "/" + y;
return futureFormattedDate
}
$("#countdown").countdown({
date: "1 April 2017 09:00:00", // Change this to your desired date to countdown to
format: "on"
});
});

I am trying to make a countdown timer for my website and I have all the coding done, but the timer does not show up. Im doing it in dreamweaver

Here is my HTML code i used this website to help me do the code but i still cant get the code to work. This is for my personal website that I am making for me and my friends.
http://forum.codecall.net/topic/51639-how-to-create-a-countdown-timer-in-javascript/
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>final proj</title>
<script type="text/javascript" src="Timer.js" />
</head>
<body>
<div id='timer' />
<script type="text/javascript">window.onload = CreateTimer("timer",30);
</script>
<body>
<div id='timer' />
<script type="text/javascript">window.onload = CreateTimer("timer",30);
</script>
</body>
</html>
Here is my javascript code
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
"use strict";
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer();
window.setTimeout("Tick()", 1000);
}
function Tick() {
"use strict";
if (TotalSeconds <=0) {
alert("Times UP!");
return;
}
TotalSeconds -= 1;
UpdateTimer();
window.setTimeout("Tick(), 1000");
}
function UpdateTimer() {
"use strict";
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) {
"use strict";
return (Time < 10) ? "0" + Time : + Time;
}
I cant get it to show up let alone countdown. I am trying to get it to display how many days,hours,minutes until a date.
Thanks in advance.
I think this is because there is an unwanted closing parentheses on the line: var TimeStr = ((Days)) ... in your code which throws an error and hence nothing works.
Also, there was a problem in your setTimeout call as stated by #taxicala.
Take a look at the working snippet below:
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("Times 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;
}
CreateTimer('timer', 5);
<div id="timer" />
Hope this helps.
setTimeout receives either a reference to a function or an anonymous function as the first parameter and an integer with the amount of desirable miliseconds after which the function should be executed from the event loop as the second parameter.
This:
window.setTimeout("Tick(), 1000");
Should be:
window.setTimeout(Tick, 1000);
You are passing a string instead of the two needed parameters.
You can, however, pass a string as the first parameter, that would look like this:
window.setTimeout("Tick()", 1000);

Javascript Countdown not working

I have this javascript code
function updateClock() {
time = time + 1;
var mins = 1;
var secs = 50
var mins = parseInt(mins/ 60);
var secs = time - mins * 60;
mins = mins.toString();
secs = secs.toString();
if (mins.length < 2)
mins = "0" + mins;
if (secs.length < 2)
secs = "0" + secs;
var timeDisp = document.getElementById("timerDisp");
timeDisp.innerText = mins + ":" + secs;
}
It is counting how much time has passed, but what if I want to do a countdown? (or do the reverse) instead of keeping track of the time, I want to give if a definite time then as time goes by the time decreases, let's say 1 minute and 15 seconds, how would I execute that on the given code?
You can execute your updateClock() every 1 second with setTimeout() to create a countdown.
var time;
function UpdateClock() {
time = time - 1;
if (time > 0) {
setTimeout(UpdateClock, 1000); // 1000 miliseconds
}
var mins = parseInt(time / 60, 10);
var secs = time - mins * 60;
mins = mins.toString();
secs = secs.toString();
if (mins.length < 2)
mins = "0" + mins;
if (secs.length < 2)
secs = "0" + secs;
timeDisp.innerText = mins + ":" + secs + " left";
}
function StartCountdown(countdowntime) {
time = countdowntime;
updateClock();
}
You could use setInterval() for your countdown. See http://www.w3schools.com/jsref/met_win_setinterval.asp.

Categories