Creating a counter - javascript

I'm creating a counter and I'm having a hard time making it.
The goal of the counter is that for ever second passed a number will increase by 170.
As you can see below the number does not add up and is made on a new line, mostly because I dont know how to make it add up. Some thing like this clock from The Economist
<!DOCTYPE html>
<html>
<body>
<p>Click the button see how much AirHelps market increases by every second.</p>
<button onclick="counterFunction()">See it now</button>
<p id="counter"></p>
<script>
function counterFunction() {
setTimeout(function () {
var text = "";
var i = 170;
while (i < 3500) {
text += "<br>The number is " + i;
i+=170;
}, 1000) }
document.getElementById("counter").innerHTML = text;
}
</script>
</body>
</html>
Any ideas on how I can make this and what is wrong with my code?

Don't use inline JavaScript (JavaScript inside HTML element attributes), it is horrible for maintainability and readability.
You seem to have a misconception about how timeouts, intervals and while loops work, what you want is an interval.
Define a count variable outside of the event listener function, then on each iteration of the interval increment the count variable by one and multiply that number by 170.
I added a little bit in there to hide the button once it has been clicked, just to stop the user from restarting the counter.
var clicker = document.getElementById('clicker');
var counter = document.getElementById('counter');
var count = 0;
clicker.onclick = function() {
setInterval(function () {
counter.textContent = "The number is " + ++count * 170;
}, 1000);
clicker.style.display = 'none';
}
<p>Click the button see how much AirHelps market increases by every second.</p>
<button id="clicker">See it now</button>
<p id="counter"></p>

http://jsfiddle.net/mblenton/Le4vxzrn/2/
function counterFunction() {
var text = ""; var i = 170; var delay = 0; var k = 1;
while (i < 3500) {
text = "The number is " + i;
i += 170;
delay = k * 1000;
doSetTimeout(text, delay);
k++;
}
}
function doSetTimeout(text, delay) {
setTimeout(function () {
document.getElementById("counter").textContent = text;
}, delay);
}

You need to use setInterval, not setTimeout`. Note that if you click the button, it will reset your timer.
You also need to declare var i and var text outside the scope of the Interval, or they will also be reset each iteration.

There were a few things wrong with your code. Among other things:
your i variable was declared in the wrong place to be reused
your closing braces were in the wrong place for the callback function
you were using a while loop, which runs synchronously, whereas you really want to just use a setInterval call.
This should work:
function counterFunction() {
var i = 170;
var text = "";
var interval = setInterval(function () {
text += "<br>The number is " + i;
i+=170;
document.getElementById("counter").innerHTML = text;
if (i >= 3500) {
clearInterval(interval);
}
}, 1000);
}
<p>Click the button see how much AirHelps market increases by every second.</p>
<button onclick="counterFunction()">See it now</button>
<p id="counter"></p>

Ok so the adder variable should be declared outside of the timeout function, because if not you are replacing the value. and you should use setInterval
var p =0;
function counterFunction(){
setInterval(function(){ p+=170;
console.log('value of p '+p);
}, 3000);
}
if you dont want to roll your own here is a nice counter
http://keith-wood.name/countdown.html

Related

Using a button to display different texts using javascript

I want to use a button to display a text with the styles and to revert to the original text when I click the button again. I have done the first part which is to display the text but I cant revert back to the original text. This is what I have so far:
function myFunction() {
document.getElementById("second").innerHTML = "Hello Javascript";
document.getElementById("second").style.fontSize = "25px";
document.getElementById("second").style.color = "red";
}
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
Declaring a a variable let count = 1; outside the function which will help me to check the state i am in currently in.so first i assigned the value of 1 to it.
in my function i am saying is count is equal to 1 change it to Hello Javascript with other properties and change count to zero.so when you click the next time count is now zero and the first if gets rejected instead it goes to the second if else
condition and makes it this is me and changes count to 1 this time.
basically changing the text with count as a statemanagement.
let count = 1;
function myFunction() {
if (count == 1) {
document.getElementById("second").innerHTML = "Hello Javascript";
document.getElementById("second").style.fontSize = "25px";
document.getElementById("second").style.color = "red";
count = 0;
} else if (count == 0) {
document.getElementById("second").innerHTML = "This is me";
document.getElementById("second").style.fontSize = "16px";
document.getElementById("second").style.color = "black";
count = 1;
}
}
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
perhaps using sequence style 😉
const sequence = [
['This is me', '20px', 'blue'],
['Hello Javascript', '25px', 'red'],
['stackoverflow', '50px', 'green'],
];
let index = 0;
function myFunction() {
const element = document.getElementById("second");
element.innerText = sequence[index][0];
element.style.fontSize = sequence[index][1];
element.style.color = sequence[index][2];
// increment the index then wrap index to the start when needed
index = (index + 1) % sequence.length;
}
// intialize
myFunction();
One way to do so would be to toggle your styles on the element. The code to do so is given below.
function myFunction() {
document.getElementById("second").classList.toggle("mystyle");
}
.mystyle {
font-size: 25px;
color: red;
}
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
<!DOCTYPE html>
<html>
<script>
var count = 0;
function myFunction() {
count += 1;
if (count % 2 > 0) {
document.getElementById("second").style.fontSize = "25px";
document.getElementById("second").style.color = "red";
document.getElementById("second").innerText = "Hello Javascript";
} else if (count % 2 == 0) {
document.getElementById("second").style.fontSize = "15px";
document.getElementById("second").style.color = "black";
document.getElementById("second").innerText = "This is me";
}
}
</script>
<body>
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
</body>
</html>
You should store the button style somewhere, and you should store your element reference, interrogating the DOM is performance consuming.
You can get compute styles with window.getComputedStyle(element)
Something like
const buttonRef = document.getElementById("second")
const buttonDefaultStyle = window.getComputedStyle(buttonRef)
const isDefaultStyle = true
let buttonInnerHTML = "text"
function myFunction() {
if (isDefaultStyle) {
buttonRef.innerHTML = "Hello Javascript";
buttonRef.style.fontSize = "25px";
buttonRef.style.color = "red";
isDefaultStyle = false;
} else {
buttonRef.innerHTML = buttonInnerHTML;
buttonRef.style.fontSize = buttonDefaultStyle.fontSize;
buttonRef.style.color = buttonDefaultStyle.color;
isDefaultStyle = true;
}
}
You have to pardon me, as I'm still learning JS, but I thought i'd give it a try as an exercise. There are probably simpler ways to do this, but this is what I came up with.
For a faux 'boolean', if you will, you can go through even and odd numbers with a counter increasing each time you press the button. If left to its own devices, a counter will go to infinity, so adding an if clause (or a case switch, could be either), for the counter if it goes above a certain number will keep it reasonable.
Rather than adding font styles, I think it would be easier to toggle between classes, that way you can just edit the CSS instead of having to go change JS every time you want to change the output style of one of the states.
Using an event listener instead of an onclick assigned to the html Button tag will allow the function to count up the clicks, because essentially the function is continually running instead of just firing once every time the button is clicked.
let counter = 0; //establishing the counter
button.addEventListener("click", function() { //using an event listener instead of an onclick event allows the function to continually run instead of firing once each time the button is clicked
let button = document.querySelector("#button");
let print1 = 'Goodbye Foo'; //making the change state the first state assigned by the click means that the content will in fact change the first time you click the button, which took me a hot second to figure out
let print2 = 'Hello World';
let printer = document.getElementById('second');
if (counter % 2 == 0) { //if the counter, when divided by two has a remainder of 0
printer.innerHTML = print1; //then print "print1" as the inner html
printer.classList.replace('print2', 'print1'); //and toggle the classes
} else { //else, if the remainder of the counter divided by 2 is not zero
printer.innerHTML = print2; //print the other state
printer.classList.replace('print1', 'print2'); //and replace the css
}
if (counter >= 9) { //if the counter ever gets to 9 (an odd number)
counter = 0; //then restart the counter at zero (which gives a remainder of 0, making it "even" in this case
} else {
counter++; //otherwise count up one each time the button is pressed
}
});
.print1 {
color: red;
font-size: 24px;
}
.print2 {
color: blue;
font-size: 12px;
}
<button id="button" type="submit">
Click me
</button>
<p id="second" class="print2">
Hello World
</p>
here it is in jsfiddle:
https://jsfiddle.net/slingtruchoice/wkt3pz9v/
you can switch from a class to another using toogle to change the style like this :
document.getElementById("second").classList.toggle("mystyle");
and you keep inner-html to change the text like this:
if (document.getElementById("second").innerHTML === "Click here")
{
document.getElementById("second").innerHTML = "Hello Javascript";
} else {
document.getElementById("second").innerHTML = "Click here";
}
I eventually used this and it worked perfectly fine for me. it also changed the text on the button as well.
let count = 1;
function mySecond() {
if (count == 1) {
document.getElementById("button3").innerHTML = "Hello Javascript";
document.getElementById("button3").classList.toggle("myStyle");
document.getElementById("button2").innerHTML = "Back";
count = 0;
} else if (count == 0) {
document.getElementById("button3").innerHTML = "This is the best";
document.getElementById("button3").classList.toggle("myStyle");
document.getElementById("button2").innerHTML = "Start";
count = 1;
}
}
<button id="button2" onclick="mySecond()">Start</button>
<p id="button3">This is the best</p>
.myStyle {
color: brown;
}

Is these a way to add 1 and then after one second than add 2 and than 3 etc

What I am looking for would essentially be a "++" to a "++" command using native java script. The program simply runs an animation for a given number in which the idea of the animatio is that it adds 1 after one second, two after two seconds and keeps going in the same fashion until the animation is stopped.
var counter = 10;
var animationOn = false;
var counterAnimation;
var plusOne;
function updateCounter() {
//update the counter value
var plusOne = counter++;
for (var i = 1; i = < 100000000;) {
}
//show the counter
var counterSpan = document.getElementById("counterHolder");
counterSpan.innerHTML = plusOne;
}
function startCounterAnimation() {
if (animationOn == false) {
animationOn == true;
counterAnimation = setInterval(updateCounter, 1000);
}
}
function stopCounterAnimation() {
if (animationOn == true) {
animationOn == false;
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="startCounterAnimation();">
Start counter animation
</button>
<button onclick="stopCounterAnimation();">
Stop counter animation
</button>
<span id="counterHolder">6931418</span>
</body>
</html>
You don't need the for loop.
You should assign to the global plusOne variable, not declare a local variable in the function.
You should add counter++ to it, not assign that directly.
Initialize plusOne from the number already in the output span.
Since your time intervals change between each update, you can't use setInterval(). Use setTimeout() to make a different timeout each time.
Use =, not ==, to assign to the animationOn variable.
var counter;
var animationOn = false;
var counterAnimation;
var plusOne = parseInt(document.getElementById("counterHolder").innerHTML);
function updateCounter() {
//update the counter value
plusOne += counter++;
//show the counter
var counterSpan = document.getElementById("counterHolder");
counterSpan.innerHTML = plusOne;
counterAnimation = setTimeout(updateCounter, counter * 1000);
}
function startCounterAnimation() {
if (!animationOn) {
animationOn = true;
counter = 1;
counterAnimation = setTimeout(updateCounter, 1000 * counter);
}
}
function stopCounterAnimation() {
if (animationOn) {
animationOn = false;
clearTimeout(counterAnimation);
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="startCounterAnimation();">
Start counter animation
</button>
<button onclick="stopCounterAnimation();">
Stop counter animation
</button>
<span id="counterHolder">6931418</span>
</body>
</html>
You can´t define var onePlus in two places, instead define it once and assign a value, var is wide scoped
Also add whatever logic you need in the for loop and put the onePlus ++ and counter as parts of the for loop
As it is now you are expecting to use the counter both outside the for loop and as the for loop middle part, which seems reduntant
Try something like(leaving the variable names as are):
var counter = 1000
for (var plusOne = 1; plusOne < counter; plusOne++) {
//Your logic in here
await sleep(1000);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

Disable the click and reset it (Javascript Vanilla)

I have a problem. I created the following code! when you click on a button, a timer that lasts 3 seconds starts, the problem is that if I double click the button, the seconds go crazy, I would like to make sure that the click is reset as soon as the timer reaches 0! so that clicking again the timer always starts from 3 seconds!
document.getElementById("titolo").style.display="block"
count = 3 ;
setInterval(function(){
count--;
if(count>=0){
id = document.getElementById("titolo");
id.innerHTML = count;
}
if(count === 0){
document.getElementById("titolo").style.display="none" ;
}
},1000);
setInterval returns an ID that you can pass to clearInterval to cancel it. When the user clicks, cancel the existing ID and call setInterval again to reset it.
Capture the return value of setInterval so that later you can use it to call clearInterval.
You should disable (or hide) the button (or other element) that the user can click to start the count down.
Make sure to always declare your variables with var, let or const.
Don't use innerHTML when you only want to assign text (not HTML entities). For text (like the string representation of a counter) use textContent.
Here is how it could work:
let start = document.getElementById("start");
let id = document.getElementById("titolo");
start.addEventListener("click", function () {
start.disabled = true;
id.style.display = "block";
id.textContent = "3";
let count = 3;
let timer = setInterval(function(){
count--;
id.textContent = count;
if (count === 0) {
id.style.display = "none" ;
clearInterval(timer);
start.disabled = false;
}
}, 1000);
});
<button id="start">Start</button>
<div id="titolo"></div>
The function setInterval returns the unique id representing the interval. You can call the function clearInterval to delete that interval.
Example:
var intervalID = setInterval(function () { }, 0);
clearInterval(intervalID);
Example combined with your code:
var intervalID, count, dom = document.querySelector("#titolo");
document.querySelector("#button").addEventListener("click", onClick);
function onClick() {
clearInterval(intervalID);
dom.style.display = "block";
dom.textContent = 3;
count = 3;
intervalID = setInterval(function() {
count -= 1;
if (count >= 0) dom.textContent = count;
else {
dom.style.display = "none";
clearInterval(intervalID);
}
}, 1000);
}
<div id="titolo"></div>
<button id="button">Button</button>

Javascript counter speeds up after the second button click

I have a counter which is activated once startnew button is clicked:
<button id="startnew" onclick="counter()">Start new Game</button>
var i = 0;
function counter() {
var execution = setInterval(function(){
active()
}, 1000);
function active() {
i++;
document.getElementById("timer").innerHTML = i;
}
}
The problem comes when I click on the startnew button for the second time, where counter starts to speed up as an inner variable stays the same.
I have tried adding additional if clauses in different parts of a code which would check if a button was already clicked but had no success so far.
How can I reset an inner variable once the same button was clicked for a second time?
You are creating a new setInterval everytime you click the button.
Call clearInterval(execution) before setInterval and make var execution global. Also Declare your variable i inside the function counter.
var execution;
function counter() {
var i = 0;
clearInterval(execution);
execution = setInterval(function() {
active()
}, 1000);
function active() {
i++;
document.getElementById("timer").innerHTML = i;
}
}
<button id="startnew" onclick="counter()">Start new Game</button>
<br>
<span id="timer"></span>
I hope i understood your Requirement...
Make the variable execution in Global Scope
var i = 0;
var execution;
function counter() {
if (i === 0) {
execution = setInterval(function() {
active()
}, 1000);
} else {
clearInterval(execution);
i = 0;
document.getElementById("timer").innerHTML = '';
}
function active() {
i++;
document.getElementById("timer").innerHTML = i;
}
}
<button id="startnew" onclick="counter()">Start new Game</button>
<span id='timer'></span>

Onclick reset setInterval

<!DOCTYPE html>
<html>
<head>
<script>
function timer(x) {
if (x == 1) {
//reset timer
}
var i = 0;
var timer = setInterval(function() {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 500);
}
</script>
</head>
<body>
<p id="demo">hello</p>
<button type="button" onclick="timer(0)">change</button>
<button type="button" onclick="timer(1)">reset</button>
</body>
</html>
I want to reset timer onclick . e.g. if setIntervaltime is set to 5 sec and 3 seconds are elapsed ,after that if some on click on reset button it should start gain from 5 seconds.How to do this.
Keep the return value of setTimeout somewhere that you can get it again (currently you are storing it in a local variable, so it goes away when the function ends)
Call clearTimeout(timer);
Call setTimeout with whatever arguments you want again.
As already Quentin mentioned, use clearInterval to solve your problem.
Wrap it within an if.else.. statement like
if(x == 1) {
clearTimeout(timeout);
}
else {
timeout = setInterval..... // otherwise even after resetting
// it will continue to increment the value
}
Complete Code:
var timeout; // has to be a global variable
function timer(x) {
var i = 0;
if (x == 1) {
clearTimeout(timeout);
document.getElementById("demo").innerHTML = i;
} else {
timeout = setInterval(function () {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 1000);
}
}
JSFiddle

Categories