JavaScript Timer Based Popup - javascript

trying to make a simple timer based popup.
once the timer reach 10 second popup will be visible.
timer should pause or stop, after clicking on 'ok' button of popup, timer should restart from 0. please help
https://jsfiddle.net/ckf0g9qj/5/
var span = document.querySelector("#time");
countDown(0);
function countDown(counter) {
var interval = setInterval(function() {
var minutes = ((counter / 60) | 0) + "";
var seconds = (counter % 60) + "";
var format = "" +
new Array(3 - minutes.length).join("0") + minutes + ':' + new Array(3 - seconds.length).join("0") + seconds;
span.innerHTML = format;
counter++;
if (seconds == 10) {
// $("#timeModal").modal(); BS model box open
// countDown(0);
document.getElementById("popup").style.visibility = "visible";
}
}, 1e3)
}
function timerReset() {
countDown(0);
alert("ok");
document.getElementById("popup").style.visibility = "hidden";
}

use clearInterval when you reach seconds == 10 condition
I think this is what you are looking for:
#popup {
width:200px;
height:200px;
border:solid 1px red;
visibility:hidden;
}
<!-- begin snippet: js hide: false console: true babel: false -->
<div id="time"></div>
<div id="popup">
<button id="ok" onclick="timerReset()">
Ok
</button>
</div>
<script>
var span = document.querySelector("#time");
countDown(0);
function countDown(counter) {
var interval = setInterval(function() {
var minutes = ((counter / 60) | 0) + "";
var seconds = (counter % 60) + "";
var format = "" +
new Array(3 - minutes.length).join("0") + minutes +
':' +
new Array(3 - seconds.length).join("0") + seconds;
span.innerHTML = format;
counter++;
if (seconds == 10) {
clearInterval(interval);
// $("#timeModal").modal(); BS model box open
// countDown(0);
document.getElementById("popup").style.visibility = "visible";
}
}, 1e3)
}
function timerReset() {
countDown(0);
alert("ok");
document.getElementById("popup").style.visibility = "hidden";
}
</script>

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/

Blinking image issues for javascript timer

I am having an issue with the timer I created. I just added in a code snippet that will cause a red rectangle to begin flashing(blinking) on the screen between 30 seconds and zero seconds. Once the timer hits zero the blinking needs to stop. The timer should only blink between 30 seconds and 0 seconds. For some reason my blinkRed() function is going haywire and I cannot figure out why. Sometimes it stops when it is supposed to other times it does whatever.
My code is below:
var seconds = 20; //Variables for the code below
var countdownTimer;
var imgBlink;
function showGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'visible';
};
function hideGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'hidden';
};
function showYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'visible';
};
function hideYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'hidden';
};
function blinkRed(){
var redBlink = document.getElementById('redStop');
if(redBlink.style.visibility == 'hidden'){
redBlink.style.visibility = 'visible';
} else {
redBlink.style.visibility = 'hidden';
}
imgBlink = setTimeout("blinkRed()", 1000);
};
function showRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'visible';
};
function hideRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'hidden';
};
function secondPassed(){
var minutes = Math.floor(seconds/60); //takes the output of seconds/60 and makes rounds it down. 4.7 = 4, 3.7 = 3. (to keep the minutes displaying right)
var remainingSeconds = seconds % 60; //takes remainder of seconds/60 and displays it. so 270/60 = 4.5 this displays it as 30 so it becomes 4:30 instead of 4.5
if (remainingSeconds < 10) { //if remaining seconds are less than 10 add a zero before the number. Displays numbers like 09 08 07 06
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds; //displays time in the html page 5:06
document.getElementById('countdown2').innerHTML = minutes + ":" + remainingSeconds; //displays the time a second time
if (seconds == 0) {
clearInterval(countdownTimer);//keeps value at zero once it hits zero. 0:00 will not go anymore
alert("Time is Up, Try again");
}
};
function changeColor(){ //this changes the background color based on the time that has elapsed
if (seconds <= 300 && seconds > 150) { //green between 5:00 - 1:30
//document.body.style.background = "url("+colorChange[0]+")";
showGreen();
}
else if (seconds <= 150 && seconds > 60) { //yellow between 1:30 - 30
//document.body.style.background = "url("+colorChange[1]+")";
hideGreen();
showYellow();
}
else if(seconds <= 60 && seconds > 30){ // red between 30 - 0
//document.body.style.background = "url("+colorChange[2]+")";
hideYellow();
showRed();
}
else if (seconds <= 30 && seconds > 0) {
hideRed();
blinkRed();
}
else if (seconds == 0){
clearTimeout(imgBlink);
}
};
function countdown(start){ //code for the button. When button is clicked countdown() calls on secondPassed() to begin count down.
secondPassed();
if (seconds != 0) { //actual code to decrement the time
seconds --;
countdownTimer = setTimeout('countdown()', 1000);
changeColor(); //calls the changeColor() function so that background changes
start.disabled = true; //disables the "start" button after being pressed
}
if (start.disabled = true){ //if one of the 'start' buttons are pressed both are disabled
start2.disabled = true;
}
//startDisabled2();
};
function cdpause() { //pauses countdown
// pauses countdown
clearTimeout(countdownTimer);
clearTimeout(imgBlink);
};
function cdreset() {
// resets countdown
cdpause(); //calls on the pause function to prevent from automatically starting after reset
secondPassed(); //reverts back to original secondPassed() function
document.getElementById('start').disabled = false; //Enables the "start" button that has been disabled from countdown(start) function.
document.getElementById('start2').disabled = false; //enables the 'start2' button. same as above.
hideGreen();
hideYellow();
hideRed();
};
#countdown{
font-size: 2em;
position: inherit;
left: 120px;
top: 5px;
}
#countdown2{
font-size: 2em;
position: inherit;
left: 120px;
top: 30px;
}
#greenGo{
visibility: hidden;
position: absolute;
bottom: 20px;
z-index: -1;
}
#yellowAlmost{
visibility: hidden;
position: absolute;
bottom: 20px;
z-index: -1;
}
#redStop {
visibility: hidden;
position: absolute;
bottom: 20px;
z-index: -1;
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="newTicket2.0.css">
<script src = "Timer2.js">
</script>
</head>
<<div id = "timerBackground">
<span id="countdown" class="timer"></span>
<div id = "timerButtons">
<input type="button" value="Start" onclick="countdown(this)" id = "start">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset(seconds = 300)">
</div>
</div>
<div id = "timerBackground2">
<span id="countdown2" class="timer"></span>
<div id = "timerButtons2">
<input type="button" value="Start" onclick="countdown(this)" id = "start2">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset(seconds = 300)">
</div>
</div>
<img src = "greenGo.png" id = "greenGo" alt = "greenGo">
<img src = "redStop.png" id = "redStop" alt = "redStop">
<img src = "yellowAlmost.png" id = "yellowAlmost" alt = "yellowAlmost">
</body>
</html>
Ive attempted to add clearTimeout(imgBlink); to just about everything I can think of and nothing seems to work. It just keeps ticking away.
Just figured it out. I added:
imgBlink = setTimeout("blinkRed()", 1000);
if(seconds == 0){
clearTimeout(imgBlink);
}
Into the blinkRed() function and now it works like a charm. Although if you press the stop button twice it continues to tick. But that is a minor issue.
Here is the updated javascript.
var seconds = 20; //Variables for the code below
var countdownTimer;
var imgBlink;
/*function startDisabled2() {
start2.disabled == true;
if (start2.disabled == true) {
start.disabled = true;
}
};*/
function showGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'visible';
};
function hideGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'hidden';
};
function showYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'visible';
};
function hideYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'hidden';
};
function showRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'visible';
};
function hideRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'hidden';
};
function blinkRed(){
var redBlink = document.getElementById('redStop');
if(redBlink.style.visibility == 'hidden'){
redBlink.style.visibility = 'visible';
} else {
redBlink.style.visibility = 'hidden';
}
imgBlink = setTimeout("blinkRed()", 1000);
if(seconds == 0){
clearTimeout(imgBlink);
}
};
/*function stopBlinkRed() {
clearInterval(imgBlink);
};*/
function secondPassed(){
var minutes = Math.floor(seconds/60); //takes the output of seconds/60 and makes rounds it down. 4.7 = 4, 3.7 = 3. (to keep the minutes displaying right)
var remainingSeconds = seconds % 60; //takes remainder of seconds/60 and displays it. so 270/60 = 4.5 this displays it as 30 so it becomes 4:30 instead of 4.5
if (remainingSeconds < 10) { //if remaining seconds are less than 10 add a zero before the number. Displays numbers like 09 08 07 06
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds; //displays time in the html page 5:06
document.getElementById('countdown2').innerHTML = minutes + ":" + remainingSeconds; //displays the time a second time
if (seconds == 0) {
clearInterval(countdownTimer);//keeps value at zero once it hits zero. 0:00 will not go anymore
alert("Time is Up, Try again");
}
};
function changeColor(){ //this changes the background color based on the time that has elapsed
if (seconds <= 300 && seconds > 150) { //green between 5:00 - 1:30
//document.body.style.background = "url("+colorChange[0]+")";
showGreen();
}
else if (seconds <= 150 && seconds > 60) { //yellow between 1:30 - 30
//document.body.style.background = "url("+colorChange[1]+")";
hideGreen();
showYellow();
}
else if(seconds <= 60 && seconds > 30){ // red between 30 - 0
//document.body.style.background = "url("+colorChange[2]+")";
hideYellow();
showRed();
}
else if (seconds <= 30 && seconds > 0) {
hideRed();
blinkRed();
}
else if (seconds == 0){
showRed();
}
};
function countdown(start){ //code for the button. When button is clicked countdown() calls on secondPassed() to begin count down.
secondPassed();
if (seconds != 0) { //actual code to decrement the time
seconds --;
countdownTimer = setTimeout('countdown()', 1000);
changeColor(); //calls the changeColor() function so that background changes
start.disabled = true; //disables the "start" button after being pressed
}
if (start.disabled = true){ //if one of the 'start' buttons are pressed both are disabled
start2.disabled = true;
}
//startDisabled2();
};
function cdpause() { //pauses countdown
// pauses countdown
clearTimeout(countdownTimer);
clearTimeout(imgBlink);
};
function cdreset() {
// resets countdown
cdpause(); //calls on the pause function to prevent from automatically starting after reset
secondPassed(); //reverts back to original secondPassed() function
document.getElementById('start').disabled = false; //Enables the "start" button that has been disabled from countdown(start) function.
document.getElementById('start2').disabled = false; //enables the 'start2' button. same as above.
hideGreen();
hideYellow();
hideRed();
};

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