Javascript countdown form submit not working - javascript

So I was trying to write some javascript to countdown and then submit the form when the countdown is finished. This is the JS I found online and tried to implement:
var seconds = 300;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60),
remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.qForm.submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
Here it is implemented:
https://jsfiddle.net/spadez/9p9o4k6s/1/
The error says: secondPassed is not defined but I'm not sure why that is. Could anyone please explain where I have gone wrong?

For me both ways of calling setInterval work well with SO snippet. I think bug can be jsfiddle specific as it seems it accepts only the first form of setInterval, which takes function and interval, not code string to execute and delay (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval). If you want to keep using fiddle you will have to change last line to:
var countdownTimer = setInterval(secondPassed, 1000);
var seconds = 300;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60),
remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.qForm.submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
body {
background-color: #eee;
}
canvas {}
time {color: red; float: right;}
.active {color: green; font-size: 12px; font-weight: bold;}
<h3>Question 1 of 20<time id="countdown">5:00</time></h3>
<form name="qForm">
<input type="radio"> 219
<input type="submit" value="Submit">
</form>

There is an error in last line of your code. Change that line to this'
var countdownTimer = setInterval(secondPassed, 1000);
Here is the updated fiddle. https://jsfiddle.net/9p9o4k6s/3/

When you pass a function call as a string to setInterval like that, the function you're calling must be in the global scope. Your function secondPassed is wrapped by the jsFiddle onload wrapper and so it is not in the global scope.
To demonstrate this, if you did window.secondPassed = secondPassed; to put it in the global scope, your existing code would work.
The proper solution is to pass the function object as the argument instead of a string:
var countdownTimer = setInterval(secondPassed, 1000);
Note there are no parenthesis () when used in this way.

Related

Does `document.getElementById` break the function?

So I am working on a pomodoro timer and can't figure out what I am doing wrong with my JS. Overview of the project is here : http://codepen.io/Ohillio/pen/wMoNWy
But the specific part of the code I am having issues with is :
// global variables
var min = 0;
var sec = 0;
function tick() {
alert("Counter Started");
sec = 59;
min--;
document.getElementById("timer").innerHTML = min + ":" + sec;
do {
sec--
document.getElementById("timer").innerHTML = min + ":" + sec;
setTimeout(donothing,500);
}
while (sec != 0);
}
The issue is that it seems like it ends the function after the first time through. I want the seconds to tick down to 0, but now it just evaluates to 58.
Does document.getElementById break the function ?
Using setInterval may be a better solution to what you're trying to do. It's going to be more accurate and easy to short circuit once you hit 0. Also, I prefer to keep the total time in seconds and only use minutes for display purposes. I've put together an example for you to review.
<script>
var interval;
var totalSeconds = 1500;
function tick() {
totalSeconds--;
min = Math.floor(totalSeconds / 60);
sec = totalSeconds % 60;
document.getElementById('timer').innerHTML = min + ':' + sec;
if (0 >= totalSeconds) {
clearInterval(interval);
}
}
interval = setInterval(tick, 1000);
</script>
Hope this helps and good luck!
This also should work, with 1 digit second format fix:
var min = 1;
var sec = 30;
function tick() {
document.getElementById("timer").innerHTML = min + ":" + (sec.toString().length < 2 ? '0' : '') + sec;
if(sec === 0 && min > 0) {
min--;
sec = 59;
setTimeout(tick, 500);
} else if (sec > 0) {
sec--;
setTimeout(tick, 500);
} else {
alert("Done!");
}
}
alert("Counter Started");
tick();

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

Putting a stopwatch on a page without using the Form tag?

The few examples I've found require a Form tag, which doesn't seem to play nicely with my existing app.
What I need to do is add a timer on my page that starts counting as soon as one button is pressed, and stops counting as soon as another button is pressed. These buttons will be outside of the UpdatePanel that the stopwatch should reside in.
Is this possible to do with Java? I found this answer which seemed promising, but wouldn't work:
How to create a stopwatch timer
It didn't seem to like the first line of the tm1_Tick function because it thought sw was NULL.
Any sample code or direction would be appreciated.
few examples I've found require a Form tag
Because they are ASP.NET WebForms (like the one you linked to: lots of server controls with namespace tag "asp").
Why not do it purely in JavaScript? On whatever event note the time, and then, using setTimeout, update the page content from time to time.
(Note the only common thing between Java – the cross platform language from Sun and now Oracle – and JavaScript – the scripting language with deep integration into browsers – is their first four letters.)
I assume you mean "JavaScript". A client-side solution will work nicely using JS.
Found this online, very nice example (disclaimer, this is not my code):
http://jsfiddle.net/oukjfavu/
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
timer();
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
I'm putting this as an answer in the interest of being perfectly clear, but it's based on Jamieson's answer. The end result was to add this Javascript:
<script type = "text/javascript">
/* Stop, Clear and Pause the timer displayed under the pause buttons */
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
document.getElementById('<%=h1.ClientID%>').innerText = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);;
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
function stp() {
clearTimeout(t);
}
function clr() {
document.getElementById('<%=h1.ClientID%>').innerText = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
</script>
The ASP.Net piece you need to add is:
<asp:UpdatePanel ID="UpdatePanel4" runat="server">
<ContentTemplate>
<table style="width:132px; margin-left:13px">
<tr>
<td style="text-align:center; margin-left:2px; border:double; background-color:darkcyan">
<asp:Label ID="h1" runat="server" ForeColor="White"><time>00:00:00</time></asp:Label>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Then, to my ASP buttons I added this:
onclientclick="stp();"
(If you already have an onclientclick on your button, just separate them with a semicolon, you can have multiple functions in an onclientclick)
I then needed to add this to a few spots in my code-behind:
ScriptManager.RegisterClientScriptBlock(UpdatePanel4, this.GetType(), "script", "stp()", true);
ScriptManager.RegisterClientScriptBlock(UpdatePanel4, this.GetType(), "script", "clr()", true);
The last piece may or may not be necessary, depending on what you're doing.
If I am understanding your question correctly, you can create your own countdown timer purely in JavaScript, then make an AJAX call to your update panel.
Here's a short example of a purely JS countdown:
var start = document.getElementById("start");
start.addEventListener("click", function() {
var interval = setInterval(function() {
var watch = document.getElementById("watch");
var value = watch.value - 1;
watch.value = value;
if (value <= 0)
clearInterval(interval);
}, 1000);
});
<input id="watch" value="10" />
<input id="start" type="button" value="start" />

How to stop timer after the the countdown is over

<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
</head>
<body>
<div id="timer">
Time Left: 00:<input id="minutes" type="text" style="width: 20px; border: none; background-color:none; font-size: 16px; font-weight: bold;">:<input id="seconds" type="text" style="width: 26px; border: none; background-color:none; font-size: 16px; font-weight: bold;">
</div>
<script>
countdown();
</script>
In this java script code the timer get executing after the time is over and time goes in minus example (00-1:30).
So I want to stop the timer when it reaches the 00:00. And it should give alert when the time is completed or submit the page.
There are a couple of issues, the biggest being that you are testing the seconds and not seconds.value, so you are always entering the else block. However, you also don't have a condition for when it reaches zero. Here is a jsfiddle that should fix those things, http://jsfiddle.net/psQb5/.
there are two possibilities. One is to use the function setInterval instead of setTimeout. Like this.
<script type="text/javascript">
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
var intervalVar;
function countdown() {
intervalVar = setInterval('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
if (secs == 0) {
window.clearTimeout(intervalVar);
alert('timeout');
}
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
use setInterval() function instead of setTimeout().
when you want to stop timer using clearInterval() function.
for basic understanding of above function click below
w3schools.

Using JQuery replaceWith with a JavaScript Variable

Here's my html:
<div class="timer">Not Started</div>
And JS/JQ:
var seconds = 10;
var minutes = 0;
setTimeout("updateTimer()", 1000);
function updateTimer() {
if (seconds == 0 && minutes != 0) {
minutes -= minutes;
seconds = 59;
alert (seconds);
} else if (seconds == 1 && minutes == 0) {
alert ('done');
} else {
seconds = seconds - 1;
//alert (seconds);
$(".timer").replaceWith(seconds);
}
setTimeout("updateTimer()", 1000);
}
Instead of replacing Not Started with 10, 9, 8..., Not Started disappears.
$(".timer").text(seconds);
You can't replace a DOM node with a string.
See an example.
You could simplify your logic further by making use of setInterval instead of setTimeout, and use total seconds for easier calculations and remove minutes.
var seconds = 10, minutes = 0;
var totalSeconds = (minutes * 60) + seconds;
var timerId = setInterval(updateTimer, 1000);
function updateTimer() {
$('.timer').text(totalSeconds % 60);
if (totalSeconds == 0) {
alert("done");
clearInterval(timerId);
}
totalSeconds--;
}
replaceWith will replace the entire div, not just the contents. Try this instead:
$(".timer").html(seconds);

Categories