How can I reset counter to 0 if value from function parameter is different in JavaScript? - javascript

I am sending value dynamically in counter function i.e, button can be counter(0), counter(1),counter(2), etc.
Now say if count = 0 (i.e, counter(0)), then I want to increment global variable i.
And now count = 1, then reset the global variable i to 0 and again start incrementing from first.
Again, say if button counter is 0 again and for counter 0 last increment was 4, then it must start from 5.
How can I do that in javascript. Is it possible to do so?
var i =0;
function counter(count){
i++;
}
<button type="button" onclick=counter(0)>Change counter</button>
var count = 0;
function myfunction() {
<button type="button" onclick="counter(` + count + `)" class="btn btn-primary rounded-0 float-right">Change Counter</button>
count++;
}

You need a separate counter for each number. You can't do this with a single global. Otherwise it resets when you change the button you click and you can never get the old value back when you go back to the previous button.
Use an object to store the counters in.
If you need to have a global value with the latest value of the most recently manipulated counter, copy the value to it afterwards.
let lastCounterValue = 0;
const counters = {};
const increment = event => {
const button = event.currentTarget;
const counterId = button.textContent;
if (!(counterId in counters)) {
counters[counterId] = 0;
}
counters[counterId]++;
lastCounterValue = counters[counterId];
console.log({
lastCounterValue,
counters
});
}
document.querySelectorAll("button").forEach(button => button.addEventListener("click", increment));
<button>0</button>
<button>1</button>
<button>2</button>
<button>3</button>

I would keep an array for each button with an unique identifier.
HTML
<button type="button" onclick="counter('a', 0)">Change counter</button>
<button type="button" onclick="counter('b', 3)"">Change counter</button>
JS
var clickArr = {};
function counter(id, count){
clickArr[id] = !isNaN(clickArr[id]) ? (clickArr[id]+1) : count;
console.log(clickArr);
}

var i = 0;
function cal() {
let cache = 0;
return function(count) {
if (count == 0) {
if (i == 0) {
i = ++cache;
// use memoized val
} else {
i++;
cache = i;
// increment
}
} else if (count == 1) {
/*set to 0, don't update cache now,
wait for next input */
i = 0;
} else {
i = count;
cache = count;
}
}
}
var counter = cal();
counter(0)
counter(0)
counter(0)
console.log('3', i)
counter(99)
console.log('99', i)
counter(1)
counter(0)
console.log('100', i)

Related

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));
}

How to make an auto clicker in JavaScript?

I'm currently making a clicker game and I wanted to know how to make a button that when I click on it, a number slowly goes up with intervals. I don't really know how to do the intervals and I've tried doing loops but loops are instant and have no intervals.
var number = 0;
function increase() {
for (var i = 0; i < 1; i++) {
document.getElementById("number").innerHTML = number += 1
}
}
<button onclick="increase()">
by 1
</button>
<div>
number:
<div id="number">
0
</div>
</div>
Can someone turn this into an auto clicker? as said above, i just want to click on the button once and have the value of the variable "number" go up. Thanks.
Here is mine showing how to
use an interval
use eventListener (unobtrusive coding)
clear the interval
how to increment a number and change speed
how to use data attributes
how to use classes and querySelector
var number = 0,
increment = 1,
speed=1000, // one second
tId;
function inc() {
clearInterval(tId); // stop anything already running
tId = setInterval(function() {
document.getElementById("number").innerHTML = number += increment;
}, speed);
}
function changeSpeed() {
speed = +this.getAttribute("data-speed"); // get attribute and convert to number
inc();
}
window.addEventListener("load", function() { // when page has loaded
document.querySelectorAll(".start").forEach(function(but) {
but.addEventListener("click", function() {
increment = +this.getAttribute("data-inc") ; // get from button and convert to number
inc()
});
});
document.getElementById("stop").addEventListener("click", function() { // when clicking
clearInterval(tId);
});
document.querySelectorAll(".speed").forEach(function(but) {
but.addEventListener("click", changeSpeed);
});
});
<button type="button" class="start" data-inc="1">By 1</button>
<button type="button" class="start" data-inc="10">By 10</button>
<button type="button" class="speed" data-speed="1000">One a sec</button>
<button type="button" class="speed" data-speed="500">Two a sec</button>
<button type="button" id="stop">Stop</button>
<div>
number: <span id="number">0</span>
</div>
function increase() {
setInterval(() => document.getElementById("number").innerHTML = number += 1, 1000)
}
setInterval() will call an anonymous function which increment the number each second (1000 ms) until you call clearInterval()
var number = 0;
function increase () {
number++;
document.getElementById('number').innerHTML = number;
}
Try this out.
I believe the issue is, you're not actually incrementing the variable 'number'. What you're instead doing is setting the content of the element number to number +=1;
So since number is 0;
it will only ever show 1 on the HTML.
If you want the number to increment by one automatically after you've clicked the button once. Create a setInterval.
setInterval(() => {
increase()
}, 5000) // increase every 5 seconds
You can set an interval with setInterval();
var number = 0;
function increase() {
for (var i = 0; i < 1; i++) {
document.getElementById("number").innerHTML = number += 1
}
}
setInterval(increase, 1000);
This should increase the number every second.
If you want to stop it then you can say:
var interval = setInterval(increase, 1000);
clearInterval(interval);
var number = 0;
function increase() {
for (var i = 0; i < 1; i++) {
document.getElementById("number").innerHTML = number += 1
}
}
<button onclick="increase()">
by 1
</button>
<div>
number:
<div id="number">
0
</div>
</div>
var number = 0,
increment = 1,
speed=1000, // one second
tId;
function inc() {
clearInterval(tId); // stop anything already running
tId = setInterval(function() {
document.getElementById("number").innerHTML = number += increment;
}, speed);
}
function changeSpeed() {
speed = +this.getAttribute("data-speed"); // get attribute and convert to number
inc();
}
window.addEventListener("load", function() { // when page has loaded
document.querySelectorAll(".start").forEach(function(but) {
but.addEventListener("click", function() {
increment = +this.getAttribute("data-inc") ; // get from button and convert to number
inc()
});
});
document.getElementById("stop").addEventListener("click", function() { // when clicking
clearInterval(tId);
});
document.querySelectorAll(".speed").forEach(function(but) {
but.addEventListener("click", changeSpeed);
});
});
<button type="button" class="start" data-inc="1">By 1</button>
<button type="button" class="start" data-inc="10">By 10</button>
<button type="button" class="speed" data-speed="1000">One a sec</button>
<button type="button" class="speed" data-speed="500">Two a sec</button>
<button type="button" id="stop">Stop</button>
<div>
number: <span id="number">0</span>
</div>
You can use setInterval(function(){ /* do something every 3 seconds */ }, 3000);
You can call the function in the interval parameter or write the code inside.
You can look at these examples.

Show elements of array one by one - Jquery

So I have a button on which I want to display each element of my array for a few seconds. This is my html code:
<button class="btn" id="random">Start</button>
I have made an array with jQuery that I want to use to change the buttons text:
$(document).ready(function() {
$("#random").on("click", loop);
});
var array = ["el1","el2","el3"];
function loop() {
for (i = 0; i < array.length; i++) {
$("#random").html(array[i]);
}
var random = Math.floor(Math.random() * array.length) + 1;
$("#random").html(array[random]);
}
The for loop is supposed to do what I want but I can't find a way to delay the speed, it always just shows the last line of code. When I try setTimeout or something it just looks like it skips the for loop.
My proposal is to use IIFE and delay:
var array = ["el1","el2","el3", "Start"];
function loop(){
for (i = 0; i < array.length; i++){
(function(i) {
$("#random").delay(1000).queue(function () {
$(this).html(array[i]);
$(this).dequeue();
});
})(i);
}
}
$(function () {
$("#random").on("click", loop);
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button class="btn" id="random">Start</button>
Basically, a for loop will not help you. It runs with the max speed it can. And delaying it would do no good in js (you would just freeze the browser). Instead, you can just make a function that will execute itself with a delay. Kinda recursion, but not entirely. Below would make the trick.
https://jsfiddle.net/7dryshay/
$(document).ready(function() {
$("#random").on("click", function (event) {
// texts to cycle
var arr = ["el1","el2","el3"];
// get the button elem (we need it in this scope)
var $el = $(event.target);
// iteation function (kinda recursive)
var iter = function () {
// no more stuff to display
if (arr.length === 0) return;
// get top of the array and set it on button
$el.text(arr.shift());
// proceed to next iteration
setTimeout(iter, 500);
}
// start first iteration
iter();
});
});
Use setInterval() and clearInterval()
$(document).ready(
function() {
$("#random").on("click", loop);
}
);
var array = ["el1", "el2", "el3"];
var int;
function loop() {
var i = 0; // variable for array index
int && clearInterval(int); // clear any previous interval
int = setInterval(function() { //store interval reference for clearing
if (i == array.length) clearInterval(int); // clear interval if reached the last index
$("#random").text(i == array.length ? 'Start' : array[i++]); // update text with array element atlast set back to button text
}, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="btn" id="random">Start</button>
UPDATE : If you need to implement it using for loop and setTimeout() then do something like this
var array = ["el1", "el2", "el3", "Start"];
function loop() {
for (i = 0; i < array.length; i++) {
(function(i) {
setTimeout(function() {
$("#random").html(array[i]);
}, i * 1000);
})(i);
}
}
$(function() {
$("#random").on("click", loop);
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button class="btn" id="random">Start</button>

jQuery/JavaScript: Initiate and terminate a loop with the same button

I want to build a button that when I click it, the function in JavaScript associated with it initiates (so a loop inside it start doing something).
If I click it again before the loop inside the function finishes, the loop will terminates.
If I click it again after the loop inside the function has already finished, the loop will just start as usual.
How do I do this with the following code?
Thanks in advance.
HTML:
<button id="startstop" class="btn btn-primary" onclick="count()">
JavaScript:
function count() {
var val = 0;
var loop = setInterval(function(){
val++;
if (val > 1000} {
clearInterval(loop);
}
}, 100);
}
try this code
var loop;
function count() {
var val = 0;
if (loop) {
clearInterval(loop);
loop = null;
}
else{
loop = setInterval(function(){
val++;
console.log(val);
if (val > 1000) {
clearInterval(loop);
loop = null;
}
}, 100);
}
}
I'm not a big fan of doing work for people, but on this occasion I'll succumb...
You need to store the internal ID outside of the function, and base your process on that. If the ID is not set, start the interval, if it is set stop the interval.
Note, that I've massively reduced the length of interval, and the number of times it fires for this example...
var _intervalId = -1;
function count() {
if (_intervalId == -1) {
var val = 0;
_intervalId = setInterval(function(){
val++;
if (val > 200) {
clearInterval(_intervalId);
_intervalId = -1
document.getElementById("output").innerHTML = "stopped automatically";
}
}, 10);
document.getElementById("output").innerHTML = "started";
} else {
clearInterval(_intervalId);
_intervalId = -1;
document.getElementById("output").innerHTML = "stopped manually";
}
}
<button onclick="count();return false">Click Here</button>
<div id="output"></div>
Place loop variable in global scope and everytime the user clicked stop previous loop if it's already started if not start it.
Hope this helps.
var loop=null;
count = function () {
var val = 0;
//Stop previous loop if it's already started
if(loop!=null){
clearInterval(loop);
loop=null;
}else{
loop = setInterval(function(){
val++;
console.log(val);
$('span').text(val);
if (val >= 20) {
clearInterval(loop);
}
}, 100);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="startstop" class="btn btn-primary" onclick="count()">Count</button>
<span>0</span>
I had fun building a small class for this. Feel free to use.
// Counter class
function Counter(callback, speed, max, init){
var loop = null;
this.callback = callback;
this.value = init || 0;
this.max = max;
function count(){
if (this.max && this.value >= this.max) {
clearInterval(loop);
loop = null;
} else {
this.value++;
}
this.callback(this.value);
}
this.start = function(){
if(!this.isStarted){
loop = setInterval(count.bind(this), speed);
}
};
this.stop = function(){
if(this.isStarted){
clearInterval(loop);
loop = null;
}
}
Object.defineProperty(this, "isStarted", { get: function(){
return !!loop;
}});
}
// Usage example.
var result = document.getElementById("counter");
var button = document.getElementById("startstop");
// Create the counter and the callback.
var counter = new Counter(function(val){
result.innerHTML = val;
}, 100, 1000);
// Init the result value.
result.innerHTML = counter.value;
// Listen for click events on the button.
button.addEventListener("click", function(){
if(counter.isStarted){
counter.stop();
} else {
counter.start();
}
});
<div id="counter"></div>
<button id="startstop">Toggle</button>

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