Javascript Function activates before button is clicked - javascript

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

Related

How to make a countdown with input field with how many minutes the countdown must go?

I have made a countdown but now I want to make a input field with how many minutes the countdown should countdown from. What I have is a pretty basic countdown but what I don't have is that a user puts the amount of minutes into the input field, click the button, and it counts down the minutes. And I hope someone can help me with this.
This is what I got so far:
(()=> {
let countdownEnded = false;
start(3600); // seconds
})();
function start(inputTime){
let startTime = Date.now();
intervalSeconds = setInterval(() => {
let currentTime = Date.now() - startTime;
if(inputTime < 1) {
stop();
} else {
updateDisplay(inputTime, currentTime);
updateMillis();
}
}, 1000);
}
function stop(){
let countDivElement = document.getElementById("countdown"); /*** Updated***/
countDivElement.innerHTML = 'countdown done';
countdownEnded = true; /*** Updated***/
}
function updateDisplay(seconds, currentTime){
let timeIncrement = Math.floor(currentTime / 1000);
updateTime(seconds - timeIncrement);
}
/**
* #method - updatesecondsond
* #summary - This updates the timer every seconds
*/
function updateTime(seconds) {
let countDivElement = document.getElementById("timer");
let minutes = Math.floor(seconds / 60);
let remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = '0' + remainingSeconds;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds > 0) {
seconds = seconds - 1;
} else {
clearInterval(intervalSeconds);
countdownEnded = true;
countDivElement.innerHTML = 'countdown done';
return null;
}
countDivElement.innerHTML = minutes + ":" + remainingSeconds + ":" ;
};
function updateMillis() {
let countMillsElement = document.getElementById('millis');
let counterMillis = 99;
let millis;
let intervalMillis = setInterval(()=> {
if(counterMillis === 1) {
counterMillis = 99;
} else {
millis = counterMillis < 10 ? '0' + counterMillis : counterMillis;
};
countMillsElement.innerHTML = millis;
counterMillis --;
}, 10);
if(countdownEnded) {
stop(); /*** Updated***/
return clearInterval(intervalMillis);
}
};
<div class="clock" id="model3">
<div id="countdown"> <!-- Updated -->
<span id="timer"></span><span id="millis"></span>
</div>
</div>
<input id="minutes" placeholder="0:00"/>
I think this may help you.
Change the following
<input id="minutes" placeholder="00"/> <button onclick="startTimer()">Start</button>
And in javascript add a new function
function startTimer(){
var x=document.getElementById("minutes").value * 60; //To Change into Seconds
start(x);
}
And remove the start function
Just add a button with click event that takes input value and triggers your 'start' function with that value as parameter. Something like this:
document.getElementById("startBtn").addEventListener("click", startTimer);
function startTimer() {
var numberOfMinutes = Number(document.getElementById("minutes").value) * 60;
start(numberOfMinutes);
}
And remove 'start' function call from the window load to prevent the timer to start immidiately.
Result is something like this:
https://jsfiddle.net/scarabs/6patc9mo/1/

Format time to minutes and seconds in countdown/timer

I am building a pomodoro clock/countdown, but have an issue with formatting selected time to minutes/hours/seconds. I have tried to multiply the secs variable with 60 (secs*=60), but it makes a mess and I can't figure out how to fix it. So, I would like it to "know" that it needs to count down from 25 minutes - in 25:00 format, or more/less(hh:mm:ss) if the user chooses so with + and - buttons. All help very appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 id="num">25 min</h1>
<div id="status"></div>
<button onclick='countDown(secs, "status")'>Start countdown</button>
<button onclick='increaseNumber()'>+</button>
<button onclick='decreaseNumber()'>-</button>
<script src="script.js"></script>
</body>
</html>
and here is javascript:
var num = document.getElementById('num').innerHTML;
var secs = parseInt(num);
function countDown(secs, elem) {
var element = document.getElementById(elem);
secs--;
var timer = setTimeout(function() {
countDown(secs, elem);
}, 1000);
//secs *= 60;
if(secs%60 >= 10){ //10 - if it's not a single digit number
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + secs%60);
}
else{
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + "0" + secs%60);
}
element.innerHTML = "Please wait for "+secs+" minutes";
//if timer goes into negative numbers
if(secs < 1){
clearTimeout(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
function increaseNumber() {
secs += 5;
document.getElementById('num').innerHTML = secs + ' min';
}
function decreaseNumber() {
if(secs >= 10) {
secs -= 5;
document.getElementById('num').innerHTML = secs + ' min';
}
}
Is there a reason you're doing it by hand ?
If you don't mind using a library, moment.js does a very good job at time manipulations. It's lightweight and very easy to use.
If you have to do it by hand because of some limitations, what are they ?
For reference:
//Creates a moment. Its value is the time of creation
var timer = moment();
//add 60 seconds to the timer
timer.add(60, 's');
//Removes 1 minutes from the timer
timer.subtract(1, 'm');
Sources :
Add
Substract
Try this countDown function:
function countDown(secs, elem) {
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" minutes";
var second = 0;
var timer = setInterval(function(){
var extraZero = second < 10 ? '0' : '';
document.getElementById('num').innerHTML = secs + ":" + extraZero + second;
if (second-- === 0) {
second = 59;
if (secs-- === 0){
clearInterval(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
}, 1000);
}
Since you are counting down the seconds, it is making more sense to use setInterval instead of setTimeout.

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

Javascript Onclick event only works once

This javascript calls up a timer that countdowns if certain variables are met. While the countdown is happening it hides the original button and replaces it with another button so that the event can't be called again during the countdown. However, after the countdown ends nothing happens when you click the button again.
<div id="set_upgrade">
<input id="upgrade" type="button" value="Upgrade" />
</div>
<div id="set_upgrading" style="display:none">
<input id="upgrading" type="button" value="Upgrade" />
</div>
<br><br><br><br>
<p id="countdown_timer"></p>
<script>
document.getElementById("countdown_timer").innerHTML = ("<span id='countdown' class='timer' style='display:block'></span>");
document.getElementById('upgrade').onclick=timer;
document.getElementById('upgrading').onclick=alert_box;
function display_timer(){
};
function alert_box(){
alert("You are currently upgrading this module.");
};
var currently_upgrading = 0;
var current_ore = 398;
var current_crystal = 398;
var upgradeTime = 3;
var seconds = upgradeTime;
var su = document.getElementById('set_upgrade');
var su2 = document.getElementById('set_upgrading');
var su3 = document.getElementById('countdown');
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;}
su.style.display = "none";
su2.style.display = "block";
su3.style.display = "block";
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) {
su.style.display = "block";
su2.style.display = "none";
su3.style.display = "none";
} else {
seconds--;
setTimeout(timer, 1000);
}
}
</script>
First of all you don't need to open and close the <script> tag every time you need to do something, then instead of doing onclick="alert_box();", try it this way.
function alert_box(){
alert("You are currently upgrading this module.");
};
document.getElementById('upgrading').onclick=alert_box;

javascript function inside function not working

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

Categories