I need to create a web page that shows two buttons: "Start" and "Stop". When "Start" is clicked, I need to display an equation every second. For example:
Suppose that the starting number is 100, then in the animation, the web page will first display:
100 + 1 = 101
And then every second after that, it should display:
100 + 2 = 102;
100 + 3 = 103;
100 + 4 = 104;
and so on...every 1 second.
I have been able to create the counter animation, however, I am stuck as to how to progress after this.
Here is my code so far
<html>
<head>
<script>
var counter = 100;
var counterSchedule;
function startCounterAnimation(){
counterSchedule = setInterval(showCounter, 1000);
}
function showCounter(){
counter = counter + 1;
var counterSpan = document.getElementById("counter");
counterSpan.innerHTML = counter;
}
function stopCounterAnimation(){
clearInterval(counterSchedule);
}
</script>
</head>
<body>
<button onClick="startCounterAnimation()">Start Animation</button>
<button onClick="stopCounterAnimation()">Stop Animation</button>
<br /><br />
<span id="counter"></span>
</body>
</html>
Any help would be greatly appreciated!
Try out with the code below. Is that what you're looking for?
var counter = 100;
var counterSchedule;
let i = 1;
function startCounterAnimation(){
counterSchedule = setInterval(showCounter, 1000);
}
function showCounter(){
counter = counter + 1;
var counterSpan = document.getElementById("counter");
counterSpan.innerHTML = `100 + ${i} = ${counter}`;
i++;
}
function stopCounterAnimation(){
clearInterval(counterSchedule);
}
<html>
<head>
</head>
<body>
<button onClick="startCounterAnimation()">Start Animation</button>
<button onClick="stopCounterAnimation()">Stop Animation</button>
<br /><br />
<span id="counter"></span>
</body>
</html>
Related
So I am trying to practice javascript and so I'm trying to do a small javascript code in which a random number is generated whenver the page loads and then the user has the option of subtracting or adding 10 from that number. The user can also input any text in the textfield and the text there will be displayed with the answer. For ex: if the random number generated is 100 and the user choose the 'subtract 10' option and wrote 'Hello' in the text field, the output will be '90Hello'.
I did most of the code, but I can't figure out how to display the answer because it doesn't work for some reason. The random number is shown but the add and subtract buttons are not working. Can someone help with that?
The code till now is:
count = 0;
let y = Math.floor(Math.random() * 100) + 1;
y = document.getElementById("numb").innerHTML;
function subtractTen() {
var t1 = document.getElementById("te");
var n1 = document.getElementById("numb") * 10;
var subtract = Number(n1.value);
var ans = subtract + t1;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function addTen() {
var t2 = document.getElementById("te");
var n2 = document.getElementById("numb") / 10;
var add = Number(n2.value);
var ans = add + t2;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function reset() {
count = countN * 0;
var res = document.getElementById("numb");
res.innerHTML = count;
}
<html>
<head>
<title></title>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen();" value="sub" /> Subtract 10 </button>
<button onClick="addTen();" value="add" /> Add 10 </button>
<button onClick="reset();" value="res" /> Reset </button>
<br />
<input name="text" id="te" />
<span id="numb" id="answer"></span>
</body>
</html>
//script.js
const container = document.getElementById('answer');
let num = generateRandom(1, 200)
let inputText = '';
function changeText() {
inputText = document.getElementById('te').value
container.innerText = inputText + num;
}
function generateRandom(min, max) {
return Math.floor(Math.random() * (max-min) + min);
}
function subtractTen() {
num -= 10;
container.innerText = inputText+num;
}
function addTen() {
num += 10;
container.innerText = inputText+num;
}
function reset() {
num = generateRandom(1, 200);
container.innerText = num
inputText = '';
document.getElementById('te').value = ''
}
container.innerText = num;
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script defer src="script.js"></script>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen()" value="sub" /> Subtract 10 </button>
<button onClick="addTen()" value="add" /> Add 10 </button>
<button onClick="reset()" value="res" /> Reset </button>
<br />
<input oninput="changeText()" name="text" id="te" />
<span id="answer"></span>
</body>
</html>
i am truly new with programing with javaScript so i just start to learn it, it will be good you are going to reply using a simple js code
my code does'nt stop when i press stop i want to clear the interval that i named with myTimer if i didn't put setInterval inside the function it just work directly and if there is any way to make my code more short please mentiot it.
const // my variable
myHour = document.getElementById("hours"),
myMin = document.getElementById("min"),
mySecond = document.getElementById("second"),
myMiliSecond = document.getElementById("dsecond"),
startchrono = document.getElementById("start"),
getLap = document.getElementById("lap"),
stopchrono = document.getElementById("stop"),
resetchrono = document.getElementById("reset"),
result = document.getElementById("result");
let // variable
milisecond = 0,
second = 0,
minute = 0,
hour = 0,
chronoRun = false,
round = 0;
function decoration(item) // this function is for add 0 if second or minute less than 10
{
if (String(item).length < 2) {
item = "0" + item;
}
return item;
}
function lapset() // function that create a new row in the table to save rounds
{
round++;
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
if (round <= 10) {
const // insert the row in table
tr = result.insertRow(-1);
tr.insertCell(0).innerHTML = round;
tr.insertCell(-1).innerHTML = h + ":" + m + ":" + s + ":" + ds;
} else if (round <= 11) {
tr = result.insertRow(-1);
tr.insertCell(-0).innerHTML = "-";
tr.insertCell(-1).innerHTML = "you can't add any more laps";
getLap.setAttribute("disabled", "true");
}
}
function chrono() //chrono start
{
// chrono
milisecond++;
// make sure that minute, second have to be less than 60
if (milisecond > 10) {
milisecond = 0;
second++;
}
if (second > 59) {
second = 0;
minute++;
}
if (minute > 59) {
minute = 0;
hour++;
}
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
myMiliSecond.innerHTML = ds;
mySecond.innerHTML = s;
myMin.innerHTML = m;
myHour.innerHTML = h;
startchrono.setAttribute("disabled", "true");
}
// function chronoStarts() {}
const myTimer = () => {
setInterval(chrono, 100);
};
const test = () => {
return clearInterval(myTimer);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);
<!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" />
<title>Document</title>
</head>
<body>
<div id="chrono">
<div id="timer">
<span id="hours" class="time">00</span>
<span class="sep">:</span>
<span id="min" class="time">00</span>
<span class="sep">:</span>
<span id="second" class="time">00</span>
<span class="sep">:</span>
<span id="dsecond" class="time">00</span>
</div>
<div id="btnarea">
<button id="start" class="btnevent">start</button>
<button id="lap" class="btnevent">lap</button>
<button id="stop" class="btnevent">stop</button>
<button id="reset" class="btnevent">reset</button>
</div>
<table id="result">
<caption>saved lap</caption>
<tbody>
<tr>
<th class="round">round</th>
<th class="laptime">time</th>
</tr>
</tbody>
</table>
</div>
<script src="newpagescript.js"></script>
</body>
</html>
and that is my html code i think every is ok with my code but if there any issue i am looking for adives
You need to get the return value of the setInterval function and then pass that value as a parameter in the clearInterval function. For example, see below:
`// function chronoStarts() {}
let intervalId = 0;
const myTimer = () => {intervalId = setInterval(chrono, 100);};
const test = () => {
clearInterval(intervalId);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);`
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title>Clicker</title>
<script type="text/javascript">
var score = 1;
}
function increase1()
{
score=score+1;
document.getElementById("clickmebtn").value = score;
}
</script>
</head>
<body>
<div id="container"><center><div id="spacer"></div><div id="btiptsish">
<input id="clickmebtn" type="submit" value="0" onmousedown="increase1()" onmouseup="increase1()"><br><br><br><br></r></div></center>
</div>
</body>
</html>
Can I use pure JavaScript to make on hold button variable increase? I want to increase variable named score.
I believe you are hopping something like this-
let score = 0;
let status = false;
const scoreEl = document.querySelector('#score');
const btnEl = document.querySelector('#btn');
let interval = null;
btnEl.addEventListener('mousedown', e => {
status = true;
update();
});
btnEl.addEventListener('mouseup', e => {
status = false;
update();
});
const update = () => {
if (status) {
interval = setInterval(() => {
score++;
scoreEl.innerHTML = score;
}, 100);
} else {
if (interval) clearInterval(interval);
}
}
<div id="score">0</div>
<button id="btn">Increment</button>
On onmousedown, create a setInterval to call the function every n miliseconds
On onmouseup, remove that interval! (clearInterval)
var interval = null;
var button = document.querySelector("#clickmebtn");
var score = 0;
button.onmousedown = function(){
addCount(); // Call function right away
interval = setInterval(addCount, 500); // Start calling every 500ms
};
button.onmouseup = function(){
clearInterval(interval); // Clear the interval if button is released
};
// Add 1 to counter and set as button value
function addCount() {
button.value = ++score;
}
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title>Clicker</title>
</head>
<body>
<div id="container">
<center>
<div id="spacer"></div>
<div id="btiptsish">
<input id="clickmebtn" type="submit" value="0"><br><br><br><br>
</div>
</center>
</div>
</body>
</html>
Use the setTimeout to set an interval and loop through it in the onmousedown event listener. I have used a seperate listener in onmouseup to clear the timeout
Below you can change the time in the setTimeout to change the interval between the score increase
var score = 0;
var timer;
function increase1()
{
timer = setTimeout(function(){
score=score+1;
document.getElementById("clickmebtn").value = score;
increase1();
}, 1000);
}
function stop() {
clearTimeout(timer);
}
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title>Clicker</title>
</head>
<body>
<div id="container"><center><div id="spacer"></div><div id="btiptsish">
<input id="clickmebtn" type="submit" value="0" onmousedown="increase1()" onmouseup="stop()"><br><br><br><br></r></div></center>
</div>
</body>
</html>
I'd do this by changing your onmousedown event to [start an interval][1], which calls your increase1() method repeatedly until the [interval is cleared][2] with onmouseup.
You can do this with a busy loop (e.g. while(true)) but that would block the UI thread and your page would become unresponsive. Using intervals avoids this.
Your example, updated to use this approach:
var score = 1;
function increase1() {
score = score + 1;
document.getElementById("clickmebtn").value = score;
}
var increaseDelay = 10; // increase score once every 10ms (prevents blocking UI thread with busy loop)
var interval = null;
function turnCounterOn() {
interval = setInterval(increase1, increaseDelay);
}
function turnCounterOff() {
clearInterval(interval);
}
<div id="container">
<center>
<div id="spacer"></div>
<div id="btiptsish">
<input id="clickmebtn" type="submit" value="0" onmousedown="turnCounterOn()"
onmouseup="turnCounterOff()">
<br><br><br><br>
</div>
</center>
</div>
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval
I meet a problem like when I try to enter a number like 30, and count it down until 0, but it doesn't work.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>123</title>
<script type="text/javascript">
function startTimer()
{
seconds = seconds - 1;
if (seconds <= 0)
{
seconds = 0;
}
else
{
seconds--;
}
var obj = document.getElementById("timer");
obj.display.value= seconds;
}
</script>
</head>
<body>
<form id="timer" action="#">
<p><input type="text" name="display" size="
20" /></p>
<p><input type="button" value="Start"
onclick="Id=setInterval('startTimer()', 100)" />
</form>
</script>
</body>
</html>
I think the problem is in if else statement, I am not sure if I make the user input correct.
Just assign 'seconds' to the current value of obj.display.value at he start of startTimer() and make sure to give the seconds input a 'number' type and a starting value.
Also use clearInterval(Id) to stop the timer once its finished..
function startTimer()
{
var obj = document.getElementById("timer");
/* make sure to tell javascript that 'seconds' is Number that
comes from the input box */
var seconds;
seconds = Number(obj.display.value);
/* Don't need this *AND* seconds-- */
// seconds = seconds - 1;
if (seconds <= 0)
{
clearInterval(Id);
seconds = 0;
}
else
{
seconds--;
}
obj.display.value = seconds;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>123</title>
<script type="text/javascript">
</script>
</head>
<body>
<form id="timer" action="#">
<p><input type="number" name="display" size="
20" value="30" /></p>
<!-- changed the interval from 100ms to 1000ms -->
<p><input type="button" value="Start"
onclick="Id=setInterval('startTimer()', 1000)" />
</form>
</script>
</body>
</html>
You can use something like this:
modify the number to whatever you want, if you want an input control then I assume you know how to do it, if not let me know.
function myFunction() {
var inputVal = document.getElementById('myInput').value;
var seconds = inputVal, $seconds = document.querySelector('#countdown');
(function countdown() {
$seconds.textContent = seconds + ' second' + (seconds == 1 ? '' : 's')
if(seconds --> 0) setTimeout(countdown, 1000)
})();
}
<input type="text" id="myInput" placeholder="Enter number..." >
<button onclick="myFunction()">Start Counter</button>
<span id="countdown"></span>
asign seconds at the top of the code...
<script type="text/javascript">
seconds =100;
<input type="number" id="inp">
<div id="counter"></div>
<script>
let input = document.getElementById('inp')
let counter = document.getElementById('counter')
let handleInput = e => {
let num = Number(e.target.value)
let _counter = num - 1
let timer = setInterval(_ => {
if(!_counter)
clearInterval(timer)
counter.innerText = _counter
_counter--
}, 1000)
}
input.addEventListener('input', handleInput)
</script>
The above logic works for 1 - 9 (single-digit input), you can add a debounce if you want to go for double-digit or greater numbers
I have a counter in javascript right now and a button that adds 1 value to the counter, this is what I have so far:
var counter = 0;
var a = 0;
var add = function(valueToAdd){
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
Value $<span id="Value">0</span>
<button width="500" height="500" id = add class="button button1" onclick="javascript:add(1)">Add Value</button>
I need a button to reset the counter back to 0 any help is appreciated.
Add a button, reset function and set values to "0" as shown in code below:
<button width="500" height="500" id ="reset" class="button button1"
onclick="javascript:reset()">Reset Value</button>
<script type="text/javascript">
var reset= function(){
a = 0;
document.getElementById('Value').innerHTML = a;
}
</script>
BTW you declared var count = 0 in your code (question) but not using that (apparently).
Some tips:
You correctly stored a variable to keep track of the counter, all you needed to do in a reset function was to change the value back to 0.
Keep your Javascript away from your HTML. Here's a good article
Your code should be properly formatted when posting on Stack Overflow.
Here's a cleaner solution:
HTML:
Value $<span id="Value">0</span>
<button id="add">Add Value</button>
<button id="reset">Reset</button>
Javascript:
var a = 0;
var add = function(valueToAdd) {
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
var reset = function() {
a = 0;
document.getElementById('Value').innerHTML = 0;
}
var addButton = document.querySelector("#add");
var resetButton = document.querySelector("#reset");
addButton.addEventListener("click", function() {
add(1);
})
resetButton.addEventListener("click", function() {
reset();
})
JSFiddle: https://jsfiddle.net/sfh51odm/
Do not define a out of function as a general variable. Every time set the current value to a and continue. So you can get back to zero:
var counter = 0;
var add = function(valueToAdd){
var a = parseInt(document.getElementById('Value').innerHTML);
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
function reset(){
document.getElementById('Value').innerHTML=0;
}
Value $<span id="Value">0</span>
<button width="500" height="500" id = add class="button button1" onclick="javascript:add(1)">Add Value</button>
<button width="500" height="500" id = add class="button button1" onclick="javascript:reset()">Reset</button>
var a = 0;
var displayValue = document.getElementById('Value');
var updateValue = function () {
displayValue.innerHTML = a;
};
var add = function (valueToAdd) {
a += valueToAdd;
updateValue();
};
var reset = function () {
a = 0;
updateValue();
};
Value $<span id="Value">0</span>
<button onclick="add(1)">Add 1</button>
<button onclick="reset()">Reset</button>
if you need to do a page refresh (like if you press F5 on the keyboard) this will work for you.
the "location.reload();" will work also.
change '.again' to a btn name you want.
document.querySelector('.again').addEventListener('click', function () { location.reload(); });