Problem with the countdown timer JS - IF Condition - javascript

I'm new to JavaScript and this website.
I have the following code for an event timer countdown:
https://codepen.io/iraffleslowd/pen/povGNdo
My problem really is with an if condition.
setInterval(function () {
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
Because my event does not expire at the end of the countdown, it ends approximately one hour after starting.
So can someone help me add another condition so that in the interval of that time instead of showing me Expired, it shows Live or something similar?
Thank you so much!

You want to manage 3 different states...
Counting down until LIVE
LIVE
EXPIRED
(() => {
const intervalId = setInterval(() => {
// update countdown timer
if (distance < -(ELAPSED_GAMETIME_IN_MS)) {
// set EXPIRED
clearInterval(intervalId);
}
else if (distance < 0) {
// set LIVE
}
}, 1000);
})();
EDIT
Working example
This example utilizes moment because it's a great utility that provides all necessary math and formatting for dates and is perfect for this scenario.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<div id="countdown"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<script>
(() => {
const countdownEl = document.getElementById("countdown");
const START_DATE = moment("2020-01-22");
const ELAPSED_GAMETIME_IN_MS = 1000 * 60 * 60 * 2; // 2 hours in milliseconds
const intervalId = setInterval(() => {
const TIME_FROM_START = START_DATE.diff(moment());
countdownEl.innerHTML = START_DATE.fromNow(); // This could be modified to show different levels of granularity...
if (TIME_FROM_START < -ELAPSED_GAMETIME_IN_MS) {
countdownEl.innerHTML = "EXPIRED";
clearInterval(intervalId);
} else if (TIME_FROM_START < 0) {
countdownEl.innerHTML = "LIVE";
}
}, 1000);
})();
</script>
</body>
</html>

It looks like an else-statement can resolve your issue.
Try
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
else {
document.getElementById("demo").innerHTML = "LIVE";
}

Related

Why two timers starts javascript issue, when timer start & I press some another timer at that time both timers are running

So here I create one contdown web application using HTML, CSS and JS and now I am stuck that how to reset the intervel time out function when click on some another button.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Countdown Timer</title>
<link href='https://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="timer">
<div class="timer__controls">
<button data-time="20" value="20" class="timer__button">20 Secs</button>
<button data-time="300" value="300" class="timer__button">Work 5</button>
<button data-time="900" value="900" class="timer__button">Quick 15</button>
<button data-time="1200" value="1200" class="timer__button">Snack 20</button>
<button data-time="3600" value="3600" class="timer__button">Lunch Break</button>
<form name="customForm" id="custom">
<input id="customMin" placeholder="Enter Minutes" >
</form>
</div>
<div class="display">
<h1 id="display__time-left">00:00</h1>
<p id="display__end-time">Be Back At 00.00</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Here in the script.js file as I mantioned , javascript uses the setTimeout feature of javascript to build one countdown web application and now when in a output browser I press Lunch time button it will show the timer for the next 1Hour and than it is stop in 00:00...
as I want if one timer is running and I press some another button or some custom input for taking seconds than at that time both timers are running.
So please provide the solution that what I have to do.
scripts.js
let allButtons = document.querySelectorAll(".timer__button");
let valueOfTime;
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener("click", function () {
valueOfTime = this.value;
BackAt();
});
}
setInterval(function () {
var minutes = Math.floor(valueOfTime / 60);
var seconds = valueOfTime % 60;
if (valueOfTime > 0) {
document.getElementById("display__time-left").innerHTML = minutes + ":" + seconds;
}
else{
document.getElementById("display__time-left").innerHTML = "00:00";
}
valueOfTime--;
}, 1000);
document.getElementById("customMin")
.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
event.preventDefault();
let inputMin = document.getElementById("customMin").value *60;
inputBackAt(inputMin);
setInterval(function () {
var minutes = Math.floor((inputMin / 60));
var seconds = inputMin % 60;
if (inputMin > 0) {
document.getElementById("display__time-left").innerHTML =
minutes + ":" + seconds;
}
inputMin--;
}, 1000);
}
});
function BackAt() {
var minutes = Math.floor(valueOfTime / 60);
let currentHours=new Date().getHours();
let currentMin= new Date().getMinutes();
let x = currentMin + minutes;
if (x > 59) {
let remainingMinutes = x-60;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours+1} : ${remainingMinutes}`;
}
else{
let remainingMin =currentMin+minutes;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours} : ${remainingMin}`;
}
}
function inputBackAt(inputMin){
var minutes = Math.floor((inputMin/ 60));
let currentHours=new Date().getHours();
let currentMin= new Date().getMinutes();
let y = currentMin + minutes;
if (y> 59) {
let remainingMinutes = y-60;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours+1} : ${remainingMinutes}`;
}
else{
let remainingMin =currentMin+minutes;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours} : ${remainingMin}`;
}
}
when I click on one button and the timer is running , after some time when I press another button to start the new timer at that time both previous and current timer are running.
This defines a Timer class that instantiates an independent timer, then create multiple copies of it. The time for each timer as well as how long a "tick" can both be supplied as arguments to the constructor. Each time the timer ticks it can call the optional updateCallback to notify you.
The example starts three timers, one for three "minutes" (a minute it actually set to 3 seconds) that ticks every second, one for six "minutes" that ticks every 500 milliseconds and one for 15 "minutes" that ticks every 200 milliseconds.
Timer (seconds, period, update, reset)
seconds: How many seconds the timer should last
period: How long a "tick" is
update: [Optional] A callback that is called after every tick
reset: [Optional] A callback back that will be called when the timer ends (or if Timer.reset() is called)
let oneSecond = 500; // this should be 1000, set to 500 for the example
let oneMinute = 3; // this should be 60, set to 3 for the example
let sessionTime = 3;
function Timer(seconds, period, updateCallback, resetCallback) {
this.s = seconds;
this.p = period || oneSecond;
this.update = updateCallback || Function.prototype; // Use NOOP function as default
this.callback = resetCallback || Function.prototype; // Use NOOP function as default
this.reset = function() {
this.intervalId = clearInterval(this.intervalId)
this.callback()
}
this.start = function() { this.update(this.s); this.intervalId = setInterval(this.timer.bind(this), [ this.p ]) }
this.timer = function() { if (--this.s <= 0) this.reset(); this.update(this.s) }
}
function setTimeLeft(sec, id) {
document.getElementById(id || 'time-left').textContent = `${(''+ ~~(sec / oneMinute)).padStart(2, '0')}:${(''+ sec % oneMinute).padStart(2, '0')}`;
}
document.addEventListener("DOMContentLoaded", function() {
new Timer(sessionTime * oneMinute, 1000, setTimeLeft, () => console.log('check 1000ms')).start()
new Timer(6 * oneMinute, 500, (s) => { setTimeLeft(s, 'time-left2')}, () => console.log('check 500ms')).start()
new Timer(15 * oneMinute, 200, (s) => { setTimeLeft(s, 'time-left3')}, () => console.log('check 200ms')).start()
})
<span id='time-left'></span><br />
<span id='time-left2'></span><br />
<span id='time-left3'></span>

How to initiate this timer with an image button?

I have a 30 second timer and an image. I want the timer to only commence when the image is clicked, i.e. an image button - how do I go about this?
This is how I currently have the timer, with displays on the page itself:
<h2>Countdown left: <span id="timer"></span></h2>
And this is the image:
<img id="img" src="image.gif" />
My timer is JS:
var seconds = 30;
var countdown = setInterval(function() {
seconds--;
document.getElementById("countdown").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000);
How can I combine the two?
You can add click event listener to the image, which will initiate the timer. Also, I have added {once: true} so that the function would execute only once (else it will bug out the timer).
document.querySelector("#img").addEventListener("click", () => {
var countdown;
var seconds = 30;
countdown = setInterval(function() {
seconds--;
document.getElementById("timer").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000)
},{ once: true});
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="https://assets.stickpng.com/thumbs/59060d740cbeef0acff9a660.png" />
If you want to reset the timer on each click, you need to clearInterval before setting another.
var countdown;
document.querySelector("#img").addEventListener("click", () => {
if (countdown) {
clearInterval(countdown);
}
var seconds = 30;
countdown = setInterval(function() {
document.getElementById("timer").textContent = seconds;
seconds--;
if (seconds <= 0) clearInterval(countdown);
}, 1000)
});
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="https://assets.stickpng.com/thumbs/59060d740cbeef0acff9a660.png" />
let timer;
const onClick = () => {
// Initial seconds
let count = 30;
// Element where the count down needs to be displayed
const element = document.querySelector('#timer');
// Remove the timer if it already exists. This would be helpful
// in case the user clicks again on the image. When User clicks
// again on the image, the existing timer is reset
if (timer) {
clearInterval(timer);
}
//Display the initial value i.e. 30 in this case
element.textContent = count;
//Decrease the timer by a second using setInterval
timer = setInterval(() => {
count -= 1;
// If counter is less than or equal to zero, then
// remove the existing count down and perform the logic
// of what should happen when the count down completes
if (count <= 0) {
clearInterval(timer);
element.textContent = '';
return;
}
element.textContent = count;
}, 1000);
}
// Attaches the click event on the image
const image = document.querySelector('#img');
if (image) {
image.addEventListener('click', onClick)
}
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="https://picsum.photos/200" />
If you wrap your existing js in a function, you can add it as a method for the click event listener on the button.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="image.gif" />
<script>
function count(){
var seconds = 30;
var countdown = setInterval(function() {
document.getElementById("timer").textContent = seconds;
seconds--;
if (seconds < 0) clearInterval(countdown);
}, 1000);
}
document.getElementById('img').addEventListener('click', count)
</script>
</body>
</html>
i think you need to create one function on click of image :
HTML
<img id="img" src="image.gif" onclick="StartTimer()" />
<script type="text/javascript">
function StartTimer() {
var seconds = 30;
var countdown = setInterval(function() {
seconds--;
document.getElementById("countdown").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000);
}
</script>
function startTimer() {
var seconds = 30;
var countdown = setInterval(function() {
seconds--;
document.getElementById("timer").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000);
}
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="image.gif" onClick="startTimer()" />
You can try wrapping the setInterval in a function and call that function on click of image

How to make stop button in Javascript to stop everything

I intended to make a Countdown Time, but I'm getting a problem. I tried a lot but I'm getting nothing. Please help me to get out of this situation.
I want to make a stop button that resets every value of variable and also stops sound when I click on the stop button.
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<!-- <script src="./script.js"></script> -->
<title>Timer</title>
</head>
<body>
<input type="number" id="time-number" placeholder="Enter Seconds" />
<h3>Time Left <span id="time-left"></span></h3>
<button id="start-button">Start</button>
<button id="stop-button">Stop</button>
<script>
document.addEventListener("DOMContentLoaded", () => {
const timeLeftDisplay = document.querySelector("#time-left");
const startButton = document.querySelector("#start-button");
const stopButton = document.querySelector("#stop-button");
var myAudio = new Audio("./sounds.mp3");
function countDown() {
var timeleft = document.getElementById("time-number").value;
console.log(timeleft);
setInterval(function () {
if (timeleft <= 0) {
clearInterval((timeleft = 0));
myAudio.play();
}
timeLeftDisplay.innerHTML = timeleft;
timeleft -= 1;
}, 1000);
}
startButton.addEventListener("click", countDown);
stopButton.addEventListener("click", () => {
myAudio.pause();
});
});
</script>
</body>
</html>
you are not using correctly the clearInterval function, it spects the id of an interval to clear. keeping a variable on top of the function will help you to track the intervals.
added some comments to improve the code
document.addEventListener("DOMContentLoaded", () => {
let intervalId = null;
const timeLeftDisplay = document.querySelector("#time-left");
const startButton = document.querySelector("#start-button");
const stopButton = document.querySelector("#stop-button");
const myAudio = new Audio("./sounds.mp3");
function countDown() {
// clear an old interval just in case the user clicks several times the start button
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
var timeleft = document.getElementById("time-number").value;
// this is to show inmediatly the counter and start counting
timeLeftDisplay.innerHTML = timeleft;
timeleft -= 1;
intervalId = setInterval(function() {
if (timeleft <= 0) {
// here we use the interval Id to clear the interval.
clearInterval(intervalId);
intervalId = null;
myAudio.play();
}
timeLeftDisplay.innerHTML = timeleft;
timeleft -= 1;
}, 1000);
}
startButton.addEventListener("click", countDown);
stopButton.addEventListener("click", () => {
document.getElementById("time-number").value = ""
timeLeftDisplay.innerHTML = ""
myAudio.pause();
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<!-- <script src="./script.js"></script> -->
<title>Timer</title>
</head>
<body>
<input type="number" id="time-number" placeholder="Enter Seconds" />
<h3>Time Left <span id="time-left"></span></h3>
<button id="start-button">Start</button>
<button id="stop-button">Stop</button>
</body>
</html>

setInterval implementation problems

I am trying to implement a function that changes the value of a variable (paddle speed in a simple pong game) but the timer is running very fast and the paddle speed doesn't seem to be changing correctly.
I've created a function that executes each time the start game button is pressed, which I'm using as a timer:
function setTimer () {
setInterval(function () {
trialWindow += 1;
}, 1000);
console.log(trialWindow);
}
This timer is executed by pressing the start button
startBtn.addEventListener('click', setTimer);
I have another function set up to increment canvas.paddleOneVelocityY whenever the trialWindow variable is a multiple of 15
function userSpeed () {
if (trialWindow % 15 === 0)
{canvas.paddleOneVelocityY = getRandomNumber(5, 20)};
console.log(canvas.paddleOneVelocityY);
}
these functions are called in the startGame function:
function startGame() {
gameInProgress = true;
gameplay.className = '';
startMenu.className = '';
gameOverMenu.className = '';
pauseMenu.className = '';
gamePaused = false;
gameInterval = window.setInterval(function() {
moveEverything();
drawEverything();
setTimer();
userSpeed();
}, 1000/fps);
}
I've tried moving setTimer and userSpeed to different positions in the order of functions called in gameInterval and the timer seems to stop completely.
any help would be very much appreciated!
setTimer creates a new interval timer (a timer that repeats) every time it's called. You're calling it from inside the callback of another interval timer:
gameInterval = window.setInterval(function() { // <== This function repeats
moveEverything();
drawEverything();
setTimer(); // <== This creates a repeating
userSpeed(); // timer every time it's called
}, 1000/fps);
Instead, just call setTimer once, when you want to start the timer it starts.
Regarding your outer timer running at 1000/fps milliseconds, you might want to look at requestAnimationFrame.
Here is what you want:
function setTimer() {
setInterval(function () {
trialWindow += 1;
userSpeed();
console.log(trialWindow);
}, 1000);
}
function userSpeed() {
if (trialWindow % 15 === 0) {
canvas.paddleOneVelocityY = getRandomNumber(5, 20)
};
console.log(canvas.paddleOneVelocityY);
}
function startGame() {
gameInProgress = true;
gameplay.className = '';
startMenu.className = '';
gameOverMenu.className = '';
pauseMenu.className = '';
gamePaused = false;
setTimer();
gameInterval = window.setInterval(function () {
moveEverything();
drawEverything();
}, 1000 / fps);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="startGame()">Start</button>
</body>
</html>

Stop jQuery timer at 0 using clearInterval

I'm having issues using clearInterval to stop my simple count timer once it is equal to 0. Essentially, timer goes past 0 into negative values instead of stopping at 0. I am creating a basic quiz that ideally will alert the user of the correct answers once the timer reaches and stops at 0.
Below is current code:
var count = 10;
var gameTime;
gameTime = setInterval("counter()", 1000);
function convertSeconds(s){
var min = Math.floor(s / 60);
var sec = s % 60;
return min + ":" + sec;
}
function counter(){
count--;
$("#timer").text(convertSeconds(count));
}
if (count === 0) {
clearInterval("#timer");
} else {
//Do nothing
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trivia</title>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div id ="timer">10</div>
</body>
Just move your if check into the counter function and clear the gameTime variable.
setInterval runs the provided function at the given interval so anything you want to run or check on that interval must happen in the provided function.
var count = 10;
var gameTime;
gameTime = setInterval("counter()", 1000);
function convertSeconds(s){
var min = Math.floor(s / 60);
var sec = s % 60;
return min + ":" + sec;
}
function counter(){
count--;
$("#timer").text(convertSeconds(count));
if (count === 0) {
clearInterval(gameTime);
} else {
//Do nothing
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trivia</title>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div id ="timer">10</div>
</body>

Categories

Resources