javascript function inside function not working - javascript

i have a timer script that i would like the user to be able to set the amount of time. it works when loading the script when the page loads and setting the timer to a default value, however when i create an input variable and a button to call the function it doesnt work. the "outside" function works however the code that i copy and paste from the working version into the function doesnt. it seems that the inside timer function is never called even though 'var countdownTimer = setInterval('secondPassed()', 1000);' is at the end of the outside function. ive been working on fixing it for hours, and i would like for a more experienced set of eyes to check it out. heres the code:
<script type="text/javascript">
function startTimer() {
var seconds = parseInt(document.getElementById("time").value);
document.getElementById('countdown').innerHTML = seconds;
function secondPassed() {
document.write(Date());
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
}
</script>
<input id="time" type="number">
<input type="button" value="Set Timer" onClick="startTimer()">
<span id="countdown" class="timer">Timer: </span>
</body>
the "Timer: " text is replaced by the value of the seconds variable but only because of the line before the inside function is defined. the Date() is not printed on the instide function

You're passing a string to setTimeout, so it gets evaluated and scope is broken. Only pass functions to setTimeout.
var countdownTimer = setInterval(secondPassed, 1000);

Related

how do i auto-submit the form when the timer comes to 00:00:00

I have used a countdown timer in my online examination website,the timer is shown via javaScript but problem is that after the 00:00:00 the timer shows negative time.I just want to stop the timer at 00:00:00 and submit a form when the time is over.below is the code that accurately displaying me the timer.
<?php
// Upon starting the section
session_start();
$_SESSION['TIMER'] = time() + 600; // Give the user Ten minutes
?>
<script type="text/javascript">
var TimeLimit = new Date('<?php echo date('r', $_SESSION['TIMER']) ?>');
</script>
<script type="text/javascript">
function countdownto() {
var date = Math.round((TimeLimit-new Date())/1000);
var hours = Math.floor(date/3600);
date = date - (hours*3600);
var mins = Math.floor(date/60);
date = date - (mins*60);
var secs = date;
if (hours<10) hours = '0'+hours;
if (mins<10) mins = '0'+mins;
if (secs<10) secs = '0'+secs;
document.body.innerHTML = hours+':'+mins+':'+secs;
setTimeout("countdownto()",1000);
if((hours==00)&&(mins==00)&&(secs==00))
document.alert("time is over");
}
countdownto();
</script>
I assume that your form has an ID attribute with this value yourForm.
// HTML
<form id="yourForm">[...]</form>
// JS
if((hours==00)&&(mins==00)&&(secs==00)) {
document.getElementById('yourForm').submit();
} else {
setTimeout(countdownto, 1000);
}
Note: Remove your setTimeout(countdownto, 1000); before the if statement
Alternative way.
You could kill the timeout with clearTimeout()
var myTimeout = setTimeout(countdownto, 1000);
if((hours==00)&&(mins==00)&&(secs==00)) {
clearTimeout(myTimeout);
document.getElementById('yourForm').submit();
}
clearTimeout documentation
Let's create a index.php file please check it. form submit on timer you can pass time through in javascript CountDown(5,div); function.
<html>
<body>
<form action="" method="post" name="mcQuestion" id="mcQuestion">
Name:<input type="test" name="name" value="Test">
<div><span id="display" style="color:#FF0000;font-size:15px"></span></div>
<div><span id="submitted" style="color:#FF0000;font-size:15px"></span></div>
</form>
<script>
var div = document.getElementById('display');
var submitted = document.getElementById('submitted');
function CountDown(duration, display) {
var timer = duration, minutes, seconds;
var interVal= setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.innerHTML ="<b>" + minutes + "m : " + seconds + "s" + "</b>";
if (timer > 0) {
--timer;
}else{
clearInterval(interVal)
SubmitFunction();
}
},1000);
}
function SubmitFunction(){
submitted.innerHTML="Time is up!";
document.getElementById('mcQuestion').submit();
}
CountDown(5,div);
</script>
</body>
</html>

Javascript Second into Minutes:Seconds

I am working on a clock that needs to display seconds into a
minutes:seconds
format.
I have worked on some auxiliary functions for display, but I have never really gotten the full display. Here is some of my code:
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = time;
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
//Timer Display
var minutes = time/60;
var second = time%60;
var display = minutes + ":" + seconds;
HTML:
<h1> Pomodoro Clock</h1>
<!--Place holder for timer-->
<div id="timer" class="circle">Timer</div>
<!--//Start Button-->
<button onclick="setTimeout(timer, 1000);">Start</button>
<!--Stop Button-->
<button onclick="stopTimer()">Stop</button>
Thie formatTime function below will take a number of seconds, and convert it to MM:SS format (including padded zeroes):
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = formatTime(time);
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
function formatTime(seconds) {
//Timer Display
var minutes = seconds / 60;
var second = seconds % 60;
return ('0'+minutes).substr(-2) +":"+ ('0'+seconds).substr(-2);
}
first of all you have to use clearInterval, then you don't update your display every second
check this fiddle out

Stopwatch Not working

I found this stopwatch tutorial online, however when i tried implementing it, it kept saying "TypeError: start is null" and "TypeError: h1 is undefined" in the console when i inspect the element. What is bugging me even further is that when i insert the code in here it works and if i put it into notepad++ it does not work. Is there a jquery file that i might have missed during the implementation and some how snippet is making it work?
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;
}
<h1><time>00:00:00</time></h1>
<button id="start" >start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
Wrap all your code, including functions, in a comon function that you could name initialize() { }.
Then, put on your <body> tag the function binded onload event like following :
<body onload="initialize()">
This will tell your code not to execute unless the whole DOM and element have been created, because you can't access your elements unless they are all fully loaded.
Likely, you have defined your Javascript BEFORE your HTML. Remember Javascript is a blocking language, so it will halt all operation (including loading the HTML) until the script is finished.
Move the script below your HTML or use some form of $(document)ready

Javascript Function activates before button is clicked

If requirements are met when you click the button it will display a count down timer. Problem is it displays the countdown timer BEFORE you even click the button. I'm not sure what I'm overlooking.
<input id="upgrade" type="button" value="Upgrade" onclick="timer();" />
<br><br><br><br>
<p id="countdown_timer"></p>
<script>
function display_timer(){
document.getElementById("countdown_timer").innerHTML = "<span id='countdown' class='timer'></span>";
}
</script>
<script>
var currently_upgrading = 0;
var current_ore = 398;
var current_crystal = 398;
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
if(currently_upgrading == 1){alert('You are already upgrading a module.');return;}
if(current_ore <= 299){alert('You need more ore.');return;}
if(current_crystal <= 299){alert('You need more crystal.');return;}
display_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;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
You need to move countdownTimer variable into your timer() function.
Try changing the last lines of timer() to be like this:
if (seconds == 0) {
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
setTimeout(timer, 1000);
}
and remove the setInterval line.
Speaking generally, setTimeout is much preferred to setInterval, because it doesn't require a managed state (countdownTimer in your example) and is far more flexible.
Also note that passing a string as in setTimeout('timer()', 1000) is obsolete, just pass a function: setTimeout(timer, ...).
This line
var countdownTimer = setInterval('timer()', 1000);
will execute 1 second after the page loads as well as on the button click and this calls the display_timer function.
you have called it in setInterval function, so it will starts immediately , because setInterval function runs after page loads and not on click and setInterval uses your function

How to set one minute counter in javascript?

In my project ,I have list of questions, for every question have three option answers.
After see the question if i want answer that question means click "show answer" button .
when I click button ,counter starts for one minute after one minute error will show .
can any one help ?
You could use something like this:
function gameLost() {
alert("You lose!");
}
setTimeout(gameLost, 60000);
UPDATE: pass function reference to setTimeout() instead of code string (did I really write it that way? O_o)
EDIT
To display the timer too (improved version, thanks to davin too):
<button onclick="onTimer()">Clickme</button>
<div id="mycounter"></div>
<script>
i = 60;
function onTimer() {
document.getElementById('mycounter').innerHTML = i;
i--;
if (i < 0) {
alert('You lose!');
}
else {
setTimeout(onTimer, 1000);
}
}
</script>
......
function timedOut() {
alert("Some error message");
}
// set a timer
setTimeout( timedOut , 60000 );
That basically sets a timer that will execute the given function after 60.000 miliseconds = 60 seconds = 1 minute
Edit: here's a quick, imperfect fiddle that also shows the countdown http://jsfiddle.net/HRrYG
function countdown() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "0:" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
}
// start the countdown
countdown();
You will want to use the setTimout function check out this article. https://developer.mozilla.org/En/Window.setTimeout Remember the timer is in milliseconds so for one minute is 60,000.
// this is the simplest way to one mint counter .this is also use in angular and oops
var i=60;
function coundown(){
setInterval(() => {
if (this.i == 0) {
return;
}
console.log(this.i--);
}, 1000);
}
// this function you can call when otp is comming or form submit and waiting for otp countdown
angular #javascript #typescript
you can try to use this
or visit for more details Demo
Demo2
function countdown() {
var seconds = 59;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML =
"0:" + (seconds < 10 ? "0" : "") + String(seconds);
if (seconds > 0) {
setTimeout(tick, 1000);
} else {
document.getElementById("verifiBtn").innerHTML = `
<div class="Btn" id="ResendBtn">
<button type="submit">Resend</button>
</div>
`;
document.getElementById("counter").innerHTML = "";
}
}
tick();
}
countdown();
<div class="btnGroup">
<span class="Btn" id="verifiBtn">
<button type="submit">Verify</button>
</span>
<span class="timer">
<span id="counter"></span>
</span>
</div>

Categories