how to choose a number to decrement below zero - javascript

I'm learning js. I want to make an alarm clock app. Currently I'm working on setting the time. I created buttons that increment and decrement the hour. I want to decrement below zero to 23. I also want to stop the increment at 23 and then continue with 0. Can anyone help me? If someone tells me the first part of the condition, I'll be able to figure out the other part.
let myHour = document.querySelector(".hours");
let myHourConverted = Number(myHour.innerText);
const hourDecrementBtn = document.querySelector(".hour-decrement");
const hourIncrementBtn = document.querySelector(".hour-increment");
hourDecrementBtn.addEventListener("click", decrementHour);
function decrementHour() {
let hourDecrement = --myHourConverted;
myHour.innerText = hourDecrement;
if (hourDecrement < 0) {
hourDecrement = 23;
}
}
hourIncrementBtn.addEventListener("click", incrementHour);
function incrementHour() {
let hourIncrement = ++myHourConverted;
myHour.innerText = hourIncrement;
if (hourIncrement > 23) {
hourIncrement = 0;
}
}
<div class="timer-hours-container">
<span class="hours">00</span>
<div class="hours-buttons-container">
<button class="hour-decrement timer-button">〈</button>
<button class="hour-increment timer-button">〉</button>

The problem is that when you make the change to decrement or increment from 23 to 0, you change the content of hourIncrement but not of myHourConverted, I leave you a small solution.
const myHour = document.querySelector(".hours");
let myHourConverted = Number(myHour.innerText);
const hourDecrementBtn = document.querySelector(".hour-decrement");
const hourIncrementBtn = document.querySelector(".hour-increment");
function decrementHour() {
if (--myHourConverted < 0) myHourConverted = 23;
myHour.innerText = myHourConverted;
}
function incrementHour() {
if (++myHourConverted > 23) myHourConverted = 0;
myHour.innerText = myHourConverted;
}
hourDecrementBtn.addEventListener("click", decrementHour);
hourIncrementBtn.addEventListener("click", incrementHour);
<div class="timer-hours-container">
<span class="hours">00</span>
<div class="hours-buttons-container">
<button class="hour-decrement timer-button">〈</button>
<button class="hour-increment timer-button">〉</button>
</div>
</div>

Related

clearInterval does not seem to be working

I'm trying to make a simple javascript counter.
Basically, I'm getting an integer value from a user by input and I want to count descending from that value to 0.
So I coded this:
let inputCounter = document.querySelector("#input-counter");
let startBox = document.querySelector(".start-box");
let startCounter = document.querySelector("#start-counter");
let errorMessage = document.querySelector("#error-message");
let timerCircle = document.querySelector(".c100");
let timeSpan = document.querySelector(".c100 > span");
startCounter.addEventListener('click', function() {
let seconds = inputCounter.value;
if (isNaN(seconds)) {
errorMessage.textContent = "Not an integer value";
errorMessage.classList.add("active");
} else {
errorMessage.classList.remove("active");
timerCircle.style.display = "block";
startBox.style.display = "none";
timeSpan.textContent = seconds;
let timerId = setInterval(() => {
seconds -= 1;
if (seconds < 0) {
clearInterval(timerId);
}
timeSpan.textContent = seconds;
}, 1000);
}
});
<div class="container">
<div class="start-box">
<input type="text" id="input-counter" placeholder="type your value in seconds">
<button id="start-counter">Start</button>
<div id="error-message"></div>
</div>
<div class="c100 p50">
<span></span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
</div>
So this works fine and properly counts down from that custom entered number but the only problem here is that it goes to -1, -2, -3 and etc.
So that is why I tried determining timerId to the setInterval function and then checking this condition:
if(seconds < 0){
clearInterval(timerId);
}
However it does not clear the interval and still shows Negative numbers...
So what's going wrong here? How can I properly clear the interval when it comes to 0?
Try this code:
let seconds = 10
let timerId = setInterval(() => {
if (seconds <= 0) {
clearInterval(timerId);
}
console.log(seconds);
seconds -= 1;
}, 1000);
Your clearInterval implementation works, but it is missing a return statement following the clear. So it clears the interval correctly (it won't run the setTimeout callback again) but the current execution of the callback continues, so it goes past the if statement and sets -1 in the label anyway. The return statement, halts the execution of that callback when you reach your base case, and leaves the label set to 0.
You could also re-arrange the code to set the label above the if statement, and change the condition to if (seconds === 0), so then following the clear and return, your seconds variable remains at 0, instead of -1.
let inputCounter = document.querySelector("#input-counter");
let startBox = document.querySelector(".start-box");
let startCounter = document.querySelector("#start-counter");
let errorMessage = document.querySelector("#error-message");
let timerCircle = document.querySelector(".c100");
let timeSpan = document.querySelector(".c100 > span");
startCounter.addEventListener('click', function() {
let seconds = inputCounter.value;
if (isNaN(seconds)) {
errorMessage.textContent = "Not an integer value";
errorMessage.classList.add("active");
} else {
errorMessage.classList.remove("active");
timerCircle.style.display = "block";
startBox.style.display = "none";
timeSpan.textContent = seconds;
let timerId = setInterval(() => {
seconds -= 1;
if (seconds < 0) {
clearInterval(timerId);
return; // THIS IS WHAT WAS MISSING
}
timeSpan.textContent = seconds;
}, 1000);
}
});
<div class="container">
<div class="start-box">
<input type="text" id="input-counter" placeholder="type your value in seconds">
<button id="start-counter">Start</button>
<div id="error-message"></div>
</div>
<div class="c100 p50">
<span></span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
</div>
If you stop when < 0, it will check:
2, reduce, its now 1, its < 0? NO, so go again
1, reduce, its now 0, its < 0? NO, so go again
1, reduce, its now -1, its < 0? yes, stop: result -1
You can stop in < 1 or <= 0.
console.log(seconds) // 0
Additionally, working with timeout and numeric variables is not so accurate (depends on instabilities in processing).
I suggest saving the start time, and calculating the difference every second.
If the PC freezes for 3 seconds, when it starts up again, 3 seconds have passed and not just 1.
let inputCounter = document.querySelector("#input-counter");
let startBox = document.querySelector(".start-box");
let startCounter = document.querySelector("#start-counter");
let errorMessage = document.querySelector("#error-message");
let timerCircle = document.querySelector(".c100");
let timeSpan = document.querySelector(".c100 > span");
startCounter.addEventListener('click', function() {
let seconds = inputCounter.value;
if (isNaN(seconds)) {
errorMessage.textContent = "Not an integer value";
errorMessage.classList.add("active");
} else {
errorMessage.classList.remove("active");
timerCircle.style.display = "block";
startBox.style.display = "none";
timeSpan.textContent = seconds;
let timerId = setInterval(() => {
console.log({seconds})
seconds -= 1;
if (seconds < 1) {
clearInterval(timerId);
}
timeSpan.textContent = seconds;
}, 1000);
}
});
<div class="container">
<div class="start-box">
<input type="text" id="input-counter" placeholder="type your value in seconds">
<button id="start-counter">Start</button>
<div id="error-message"></div>
</div>
<div class="c100 p50">
<span></span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
</div>

Need help adding max and min value to counter

I am trying to make a counter which starts at 0 and ends at 12 What I have right now is a counter that I can't cap. So basically, I am having trouble setting a max and min. Here is my code:
<div class="counter8">
<label id="blank"></label>
<div class="operations">
⇦
<span class="count8">0</span>
⇨
</div>
</div>
<script>
var add=document.querySelector(".inc");
var sub=document.querySelector(".dec");
let counter8=document.querySelector(".count8");
function inc_num8(){
var temp8=parseInt(counter8.innerText) >> 0;
counter8.innerText=temp8+1;
if (temp8 > 12) {
counter8.value = 12;
} else {
counter8.value = temp8;
}
}
function dec_num8(){
var temp8=parseInt(counter8.innerText) >> 0;
counter8.innerText=temp8-1;
}
</script>
The increase button was one of my attempt at making this work but failed.
You can use Math.max and Math.min to cap the values.
<div class="counter8">
<label id="blank"></label>
<div class="operations">
⇦
<span class="count8">0</span>
⇨
</div>
</div>
<script>
var add=document.querySelector(".inc");
var sub=document.querySelector(".dec");
let counter8=document.querySelector(".count8");
function inc_num8(){
var temp8=parseInt(counter8.innerText) >> 0;
counter8.innerText=Math.min(12,temp8+1);
}
function dec_num8(){
var temp8=parseInt(counter8.innerText) >> 0;
counter8.innerText=Math.max(0,temp8-1);
}
</script>
If you wanted to fix your code using if branching you could do:
if (temp8 >= 12) {
temp8 = 12;
} else {
temp8++;
}
counter8.innerText=temp8;
Or on one line: temp8 = temp8 >= 12 ? temp8 : temp8+1
For the minimum one just the flipped version
You didn't really limit min counter on your minus button. And also you only increment it after you check for condition.
So for you examples:
function inc_num8(){
var temp8=parseInt(counter8.innerText) >> 0;
if (temp8 >= 12) { // here changed to >=
counter8.innerText = 12; //also use innerText, not value
} else {
counter8.innerText=temp8+1;
}
}
function dec_num8(){
var temp8=parseInt(counter8.innerText) >> 0;
if(temp8 <= 0){ //here changed to <=
counter8.innerText = 0;
}else{
counter8.innerText=temp8-1;
}
}

How to fix clearInterval() not stopping the interval?

I made an interval connected to a button that only runs when you have a certain amount of money and lemonade. Then I created an if statement that makes it so that when you run out of lemonade, then the interval stops. I used clearInterval() and for some reason the interval doesn't stop, and the number of lemonade goes into the negatives. Obviously you can't have a negative amount of something!
I've looked at all of the other questions with similar problems to me, but they didn't really answer my question. They all have different variables and it was hard to find an answer pertaining to my code.
Here's my code:
let autoBtnTwo = document.getElementById("autoBtnTwo");
let lemonade = 0;
let btnTwo = document.getElementById("btnTwo")
function btnTwoCost() {
wallet.removeCash(20);
update();
document.getElementById("lemonade").innerHTML = lemonade += 30
}
function double() {
if (wallet.getCash() >= 50) {
wallet.addCash(2)
update();
document.getElementById("lemonade").innerHTML = lemonade -= 1;
}
}
function autoLemonade() {
if (wallet.getCash() >= 3000) {
wallet.removeCash(3000);
var myint = setInterval(double, 1000);
autoBtnTwo.disabled = false;
update();
}
if (wallet.getCash() <= 2999) {
autoBtnTwo.disabled = true;
}
if (lemonade <= 0) {
autoBtnTwo.disabled = true;
btnTwo.disabled = true;
}
}
function stopInterval() {
var myint = setInterval(double, 1000);
if (lemonade <= 0) {
clearInterval(myint);
stopInterval();
}
}
function thousand() {
wallet.addCash(1000)
update();
if (wallet.getCash() >= 3000) {
autoBtnTwo.disabled = false;
}
}
function Wallet() {
return {
addCash: function(val) {
number += val;
},
getCash: function() {
return number;
},
removeCash: function(val) {
number -= val;
}
}
}
var number = 0;
const wallet = new Wallet();
var SUFFIXES = 'KMBTqQsSOND';
function update() {
document.getElementById('number').textContent = getSuffixedNumber(wallet.getCash());
}
function getSuffixedNumber(num) {
var power = Math.floor(Math.log10(num));
var index = Math.floor(power / 3)
num = num / Math.pow(10, (index * 3)); // first 3 digits of the number
return num.toFixed(1) + (SUFFIXES[index - 1] || ''); // default to no suffix if it gets an out of bounds index
}
<button onclick="autoLemonade()" class="chocolate-bar-auto" id="autoBtnTwo" disabled>
Hire worker: <br> -$3000<br> Sells Lemonade
</button>
<button onclick="thousand()">to get to $3000 for testing </button>
<button onclick="btnTwoCost()"> buy lemonade -$20</button>
<button onclick="double()">sell lemonade </button>
<div class="cash-div">
Cash: <div id="number">0</div>
</div>
<div class="lemonade-div">
Lemonade: <div id="lemonade">0</div>
</div>
Sorry if this version is glitchy. All of the code I used to prevent the glitches makes the code longer, which it is already long enough. press the $3,000 button 4 times, then the buy lemonade, and then the hire worker button and you will see what happens once it gets to 0.
The interval should stop adding money, and stop reducing the amount of lemonade when lemonade reaches 0, but instead it keeps going into the negatives.

How to add a number to a var every second

As a beginner in Javascript, I'm trying to make a clicker game. I don't know how to add a number to a var every second
Below is the code at the moment. I'm not sure how to make one of my "dank miners" automatically add coins every second to the player. Let's say there are two auto miners, then the player earns 4 coins per second. Also how to display how much the player is automatically making.
Thanks!
let borkCoins = 0;
let dankMiner = 0;
const earnBork = () => {
borkCoins += 1;
displayScreen();
};
const buydankMiner1 = () => {
if (borkCoins >= 20) {
dankMiner += 1;
borkCoins -= 20;
displayScreen();
} else {
alert("Insufficient funds!")
}
};
const displayScreen = () => {
document.getElementById("bork-coins").innerText =
borkCoins;
document.getElementById("dankMiner").innerText =
dankMiner;
};
displayScreen();
<h3>Your BorkCoins: <span id="bork-coins"></h3>
<img src="https://i.pinimg.com/736x/ef/6a/cf/ef6acfc481b76637b71d4a71db7de82a--dog-birthday-animal-memes.jpg"
height="80" width="80" id="bork-coins" onclick="earnBork();">
<p>Click on Gabe the Doggo to earn a BorkCoin!</p>
<h3>Shop</h3>
<p>Dank Miner <i>(2 BorkCoins/sec)</i>
<br>Your Dank Miner(s): <span id="dankMiner"></span></p>
<button id="dank-miner" onclick="buydankMiner1();">Buy 1 (20 BorkCoins)</button>
You can use setInterval function and do something like this :
let borkCoins = 0;
let dankMiner = 0;
const earnBork = () => {
borkCoins += 1;
displayScreen();
};
/* Code Added */
setInterval(earnBork, 1000);
/*--*/
const buydankMiner1 = () => {
if (borkCoins >= 20) {
dankMiner += 1;
borkCoins -= 20;
displayScreen();
} else {
alert("Insufficient funds!")
}
};
const displayScreen = () => {
document.getElementById("bork-coins").innerText =
borkCoins;
document.getElementById("dankMiner").innerText =
dankMiner;
};
displayScreen();
<h3>Your BorkCoins: <span id="bork-coins"></span></h3>
<img src="https://i.pinimg.com/736x/ef/6a/cf/ef6acfc481b76637b71d4a71db7de82a--dog-birthday-animal-memes.jpg" height="80" width="80" id="bork-coins" onclick="earnBork();">
<p>Click on Gabe the Doggo to earn a BorkCoin!</p>
<h3>Shop</h3>
<p>Dank Miner <i>(2 BorkCoins/sec)</i>
<br>Your Dank Miner(s): <span id="dankMiner"></span></p>
<button id="dank-miner" onclick="buydankMiner1();">Buy 1 (20 BorkCoins)</button>
Add an interval that checks for the number of miners:
setInterval(() => {
if (dankMiner > 0) {
borkCoins += dankMiner;
displayScreen();
}
}, 1000);

javascript array cycling only first var

I am using javascript to cycle through an array of urls within an iframe and so far when the prev or next buttons are pressed it jumps to the first var in the array and both prev and next functions end. Any ideas?
<iframe id="myFrame" src="http://startpage.com" width="484px" height = "424px"></iframe>
<button onclick = "prevPage(); ">Prev</button>
<button onclick = "nextPage(); ">Next</button>
<script>
var sites=new Array();
sites[0]="http://site1.html";
sites[1]="http://site2.html";
sites[2]="http://site3.html";
sites[3]="http://site4.html";
function nextPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 4 ,number.length-3);
number = parseInt(number) + 1;
document.getElementById("myFrame").src=sites[0];
}
function prevPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 3 ,number.length-4);
number = parseInt(number) - 1;
document.getElementById("myFrame").src=sites[0];
}
</script>
Why are you using the URL as your 'position' storage? It'd be FAR easier to just use a variable:
var curPos = 0;
function nextPage() {
curPos++;
if (curPos >= sites.length) {
curPos = 0;
}
document.getElementById('myframe').src = sites[curPos];
}
function prevPage() {
curPos--;
if (curPos < 0) {
curPos = sites.length - 1;
}
document.getElementById('myframe'.).src = sites[curPos];
}
If I understood your problem correctly I think all you need to do is use document.getElementById("myFrame").src=sites[number]; instead of document.getElementById("myFrame").src=sites[0];
May be
document.getElementById("myFrame").src=sites[number-1];
is what you are trying to do in both functions.

Categories