setInterval doesn't work, what might be wrong? - javascript

i'm creating a count down time, and here is my piece of code, but it just doesn't work, what might i be doing wrong?
<div id="container">
<h1 id="time">0:00</h1>
</div>
<script type="text/javascript">
$(document).ready(function(){
var minutes = 1;
var secondsRemaining = minutes * 60;
intervalHandle = setInterval(tick,1000);
function tick(){
var timeDisplay = $('#time');
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
if(sec < 0){
sec = "0" + sec;
}
var message = min.toString() + ":" + sec;
timeDisplay.html(message);
if(secondsRemaining === 0){
alert('Done!');
clearInterval(intervalHandle);
resetPage();
}
}
});
</script>
`

You forgot to decrease the seconds each step :-) they are still equal to 60:
secondsRemaining--;
Here's fiddle;
http://jsfiddle.net/GhnMr/

Related

Add value from textbox to counter

I'm learning javascript and I want to create a simple clock. I want for user to be able to change minutes by entering a number in textbox and pressing a button, so when that number is displayed and when the seconds are counted to 60, that displayed number increase by 1, my code won't work, help pls:
var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
return seconds = 0;
}
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
dugme.addEventListener("click", function() {
var minutes = parseInt(document.querySelector("#value").value);
el2.innerText = minutes;
})
function incrementMinutes() {
minutes2 += 1;
if (minutes2 === 60) {
return minutes2 = 0;
}
rezultat = (seconds + minutes2 + minutes);
el2.innerText = rezultat;
}
var cancel = setInterval(incrementMinutes, 60000);
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
</form>
You have a few problems in your code. The main mistake is that your variable minutes is not defined in the function incrementMinutes() where you are trying to use it. You have to calculate it again.
Other improvements that you can make are:
Remove the return in your incrementSeconds and incrementMinutes function
Have only 1 setInterval, and call incrementMinutes when seconds reach 60.
You can see a snippet here below:
var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
seconds = 0;
incrementMinutes();
}
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
dugme.addEventListener("click", function() {
var minutes = parseInt(document.querySelector("#value").value);
el2.innerText = minutes;
})
function incrementMinutes() {
minutes2 += 1;
if (minutes2 === 60) {
minutes2 = 0;
}
rezultat = (minutes2 + parseInt(document.querySelector("#value").value));
el2.innerText = rezultat;
}
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
To show here the behavior I made a minute to 5 seconds.
As a formatting improvement, if you want to show in result min:sec you can do this
min = min < 10 ? "0"+min : min;
seconds = seconds < 10 ? "0" + seconds : seconds;
To build the string with leading zeros.
I have removed the returns because they were not neccessary you can inside reset the value there is no need to return it.
var seconds = 0;
var min = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var secCounter = document.getElementById("seconds-counter");
var mintCounter = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
seconds = 0;
}
secCounter.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
function incrementMinutes() {
min += 1;
if (min === 60) {
min = 0;
}
tempMin = min;
tempSec = seconds;
min = min < 10 ? "0"+min : min;
seconds = seconds < 10 ? "0" + seconds : seconds;
rezultat = (min+":"+seconds);
mintCounter.innerText = rezultat;
min = tempMin;
seconds = tempSec;
}
// for debugging to 5 sec
var cancel = setInterval(incrementMinutes, 5000);
dugme.addEventListener("click", function() {
var inpMinutes = parseInt(document.querySelector("#value").value);
min = inpMinutes;
mintCounter.innerText = min;
})
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
</form>

javascript dosen't read the value in html

So i want to make a program that start countingdown from a value that you choose but the issue is when i try to bring the value to javascript it dosen't work but when i type the value in html it work
here is my html code
<body>
<div id="count">
<input id="time" type="number" min="0">
<button id="button">Press here to begin the countdown</button>
</div>
<script src="lol.js"></script>
and here is my javascript code
var count = document.getElementById("count"),
seconds = document.getElementById("time").value ,
btn = document.getElementById("button"),
secondPass;
countDown = setInterval(function() {
secondPass()
} , 1000);
btn.onclick =
function secondPass(){
var minutes = Math.floor(seconds / 60),
remseconds = seconds % 60;
count.innerHTML = minutes + ":" + remseconds;
if (remseconds < 10){
remseconds = "0" + remseconds;
}
if (seconds> 0 ){
seconds = seconds - 1;
}
else {
clearInterval(countDown)
count.innerHTML = "done !"
}
}
The problem in your code was that you were trying to get the value before it was entered.
If I understood correctly, you wanted this:
var count = document.getElementById("count"),
btn = document.getElementById("button"),
secondPass;
btn.addEventListener("click", secondPass);
function secondPass() {
var seconds = document.getElementById("time").value
var countDown = setInterval(function () {
var minutes = Math.floor(seconds / 60),
remseconds = seconds % 60;
count.innerHTML = minutes + ":" + remseconds;
if (remseconds < 10) {
remseconds = "0" + remseconds;
}
if (seconds > 0) {
seconds = seconds - 1;
}
else {
clearInterval(countDown)
count.innerHTML = "done !"
}
}, 1000);
}
<div id="count">
<input id="time" type="number" min="0">
<button id="button">Press here to begin the countdown</button>
</div>
Main mistake - on time when you declare seconds variable - time input is empty.
I fixed your example, so you can figure out what was wrong
var count = document.getElementById("count"),
seconds,
btn = document.getElementById("button"),
countDown
btn.onclick = function() {
seconds = document.getElementById("time").value;
countDown = setInterval(function() {
secondPass()
}, 1000);
}
function secondPass(){
console.log('S', seconds)
var minutes = Math.floor(seconds / 60),
remseconds = seconds % 60;
count.innerHTML = minutes + ":" + remseconds;
if (remseconds < 10){
remseconds = "0" + remseconds;
}
if (seconds> 0 ){
seconds = seconds - 1;
}
else {
clearInterval(countDown)
count.innerHTML = "done !"
}
}

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/

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

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;

Categories