how to increase variable in js by holding a button? - javascript

<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

Related

Another stopwatch using JS?

The code is creating a responsive page. But every time I press stop and then start again the countdown speeds up. Seconds pass like milliseconds and mins pass like seconds after about 10 or so stops and starts. What might be the issue here?
P.S. I haven't written code for the reset button.
let ms = 0;
let secs = 0;
let mins =0;
let flag = true;
var setIntID;
watchFunction =()=> {
if(flag){
ms +=4 ;
document.getElementById('msecs').innerText = `${ms}`;
if(ms == 1000){
ms =0;
secs++
document.getElementById('secs').innerText = `${secs}:`
if(secs == 60){
mins++;
document.getElementById('min').innerText = `${mins}:`;
secs = 0;
}
}}}
document.getElementById("start").addEventListener('click', function(){
flag = true;
var setIntID = setInterval(watchFunction,1);
console.log(flag) //tracker
})
document.getElementById("stop").addEventListener('click', function(){
flag = false;
console.log(flag); //tracker
clearInterval(setIntID);
})
<div id="mainDiv">
<div>
<span id="min">0:</span>
<span id="secs">0:</span>
<span id="msecs">0</span>
<div>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="reset">reset</button>
</div>
</div>
</div>
You have declared setIntID as a local variable in click for the start button, and therefore it isn't cleared in the click function for the stopbutton.
let ms = 0;
let secs = 0;
let mins =0;
let flag = false;
var setIntID;
watchFunction =()=> {
if(flag){
ms +=4 ;
document.getElementById('msecs').innerText = `${ms}`;
if(ms == 1000){
ms =0;
secs++
document.getElementById('secs').innerText = `${secs}:`
if(secs == 60){
mins++;
document.getElementById('min').innerText = `${mins}:`;
secs = 0;
}
}}}
document.getElementById("start").addEventListener('click', function(){
if (flag) return;
flag = true;
setIntID = setInterval(watchFunction,1);
console.log(flag) //tracker
})
document.getElementById("stop").addEventListener('click', function(){
flag = false;
console.log(flag); //tracker
clearInterval(setIntID);
})
<div id="mainDiv">
<div>
<span id="min">0:</span>
<span id="secs">0:</span>
<span id="msecs">0</span>
<div>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="reset">reset</button>
</div>
</div>
</div>
I think that solves the problem.
<!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="mainDiv">
<div>
<span id="min">0:</span>
<span id="secs">0:</span>
<span id="msecs">0</span>
<div>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="reset">reset</button>
</div>
</div>
</div>
<script>
let ms = 0;
let secs = 0;
let mins =0;
let flag = true;
var setIntID;
var running_instance_count = 0;
watchFunction =()=> {
if(flag){
ms +=4 ;
document.getElementById('msecs').innerText = `${ms}`;
if(ms == 1000){
ms =0;
secs++
document.getElementById('secs').innerText = `${secs}:`
if(secs == 60){
mins++;
document.getElementById('min').innerText = `${mins}:`;
secs = 0;
}
}}}
document.getElementById("start").addEventListener('click', function(){
flag = true;
running_instance_count++;
if(running_instance_count == 1){
setIntID = setInterval(watchFunction,1);}
console.log(flag) //tracker
})
document.getElementById("stop").addEventListener('click', function(){
flag = false;
running_instance_count = 0;
console.log(flag); //tracker
clearInterval(setIntID);
})
document.getElementById('reset').addEventListener('click', function(){
flag = false;
ms=0; secs=0; mins=0;
running_instance_count = 0;
clearInterval(setIntID);
document.getElementById('msecs').innerText = `${0}`;
document.getElementById('secs').innerText = `${0}:`;
document.getElementById('min').innerText = `${0}:`;
})
</script>
</body>
</html>
I see a time boost now, but on it's it's first click it's actually slow at ms +=4 so I changed it to ms +=10. Also, there's no usage of the flag on the event handler which would help control the setInterval() and clearInterval() so that there is only one existing at a time. Everytime the "start" button was clicked in OP code there was another setInterval() added, therefore the time intervals combined accelerated. In the example, there's only one event handler that toggles between setInterval() and clearInterval().
let mil = 0;
let sec = 0;
let min = 0;
let flag = false;
let setIntID;
const form = document.forms.stopWatch;
const fc = form.elements;
const timer = () => {
if (flag) {
fc.milliseconds.value = mil += 10;
if (mil == 1000) {
mil = 0;
sec++;
if (sec < 10) sec = '0' + sec;
fc.seconds.value = sec + ' :';
if (sec == 60) {
min++;
if (min < 10) min = '0' + min;
fc.minutes.value = min + ' :';
sec = 0;
}
}
}
}
fc.toggle.addEventListener('click', function() {
if (!flag) {
flag = true;
setIntID = setInterval(timer, 1);
return
}
clearInterval(setIntID);
flag = false;
});
form.onreset = e => {
mil = 0;
sec = 0;
min = 0;
clearInterval(setIntID);
flag = false;
}
<form id="stopWatch">
<fieldset>
<output id="minutes">00 :</output>
<output id="seconds">00 :</output>
<output id="milliseconds">000</output><br>
<button id="toggle" type='button'>Start/Stop</button>
<button type="reset">Reset</button>
</fieldset>
</form>

Hide AND unhide a <div> or <form> while executing code (progress bar a.o.)

the goal is to hide a form, do some stuff and unhide the form again. For example with this code for a progress bar I thought to do the following but the hiding/unhiding doesn't work. I'm probably overseeing something obvious.
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;
function start(max) {
show_div();
button = document.getElementById("button");
count = 0;
countmax = max;
progressbar = document.getElementById("bar");
progressbar.max = countmax;
timerID = setInterval(function(){update()},10);
show_div();
}//end function
function update() {
button.innerHTML = "Counting to " + countmax;
count = count + 100;
progressbar.value = count;
if (count >= countmax) {
clearInterval(timerID);
button.innerHTML = "Ready";
progressbar.value = 0;
}//end if
}//end function
function show_div() {
var x = document.getElementById("do_you_see_me?");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}//end function
</script>
</head>
<body>
<div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
<button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
<br>
<progress id="bar" value="0"></progress>
</p>
</body>
</html>
you can hide and unhide it. the problem with your code is when you trigger ready buton it will hide and then unhide the code automatically. this is becuase setInterval() function is asynchronious function. then you need call show_div() function inside the setInterval().
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;
function start(max) {
hide_div();
button = document.getElementById("button");
count = 0;
countmax = max;
progressbar = document.getElementById("bar");
progressbar.max = countmax;
timerID = setInterval(function()
{
update()
if(count>=countmax)
{
show_div();
}
},10);
}//end function
function update() {
button.innerHTML = "Counting to " + countmax;
count = count + 100;
progressbar.value = count;
if (count >= countmax) {
clearInterval(timerID);
button.innerHTML = "Ready";
progressbar.value = 0;
}//end if
}//end function
function show_div() {
document.getElementById("do_you_see_me?").style.display="block";
}//end function
function hide_div()
{
document.getElementById("do_you_see_me?").style.display="none";
}
</script>
</head>
<body>
<div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
<button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
<br>
<progress id="bar" value="0"></progress>
</p>
</body>
</html>
i hope this will fix your problem.

How to make a modified counter animation in JavaScript?

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>

Create a countdown timer on button click when value is entered in text box : Javascript

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

HTML Button Count

Im trying to implement a logic whereby each time I click the button the count alternates between 1 and 0. In the following code the count is always 0 as each time I press the button the function sets the count to 0. Please help me out and thanks in advance
<html>
<head>
<script type="text/javascript">
function main(){
var button = document.getElementById('button');
count = 0;
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
Declare count variable at global scope.
<html>
<head>
<script type="text/javascript">
var count = 0;
function main(){
var button = document.getElementById('button');
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
Declare the button in global scope. And use the bitwise operator for toggling between 0 and 1 like this..
<script type="text/javascript">
var count = 0; //global scope
function main(){
var button = document.getElementById('button');
if(button.onclick){
alert(count);
count ^= 1; //bitwise operator
}
}
</script>
^ (Bitwise XOR) as a I/O toggler
each time you click the button, main() is called. and each time you call main() you're setting count to 0 to start. Place count outside your function scope.
I agree with Ataur's answer but you might want to consider a bool for this use case as best practise.
<html>
<head>
<script type="text/javascript">
var buttonIsOn = true;
function main(){
var button = document.getElementById('button');
if(button.onclick && buttonIsOn){
alert("turning button off");
buttonIsOn = false;
}
else { // no need to check again if using bool
alert("turning button on");
buttonIsOn = true;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
You should set the count to 0 outside of the function.
<html>
<head>
<script type="text/javascript">
var count = 0;
function main(){
var button = document.getElementById('button');
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
You need to hook click event with button and alternate between 0 & 1 on click.
function main() {
var button = document.getElementById('button');
var count = 0;
button.addEventListener("click", function() {
if (count == 0) {
alert(count);
count = 1;
}
else if (count == 1) {
alert(count);
count = 0;
}
});
}
Further make sure that main function is called on when document is in ready state or put function call to main right above closing of body tag. Something like this
<body>
<button type="button" id="button" >Click Me!</button>
<script>
main();
</script>
</body>

Categories