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.
Related
My Code
window.onload = function(){
setInterval(function(){
if (typeof document.getElementsByClassName('btn-primary')[0]!="undefined"){
document.getElementsByClassName('btn-primary')[0].click();
}
}, 1000);
}
<button type="button" class="btn-primary" >Auto click</button>
i want to click button as class="btn-primary" only 10 time. but i won't find the code for it. my code repeats clicking every 1s.
Now my question is, how can i click the button only 10 times?
If you are using setInterval function, that function will trigger each time on the specified interval, you have to use clearInterval once the limit is reached.
function clickme() {
console.log('You clicked me');
}
let intervalFunction;
let count = 0;
window.onload = function () {
intervalFunction = setInterval(function () {
if (typeof document.getElementsByClassName('btn-primary')[0] != "undefined") {
document.getElementsByClassName('btn-primary')[0].click();
count++;
if (count === 10) {
console.log("Now you have clicked me 10 times!! let me take a break")
clearInterval(intervalFunction)
}
}
}, 1000);
}
<button class="btn-primary" onclick="clickme()">Click me</button>
If you dont need to have the interval between each click, you can direcly click it with a loop.
Example
function clickme() {
console.log('You clicked me');
}
let intervalFunction;
let count = 0;
window.onload = function () {
while(count < 10) {
if (typeof document.getElementsByClassName('btn-primary')[0] != "undefined") {
document.getElementsByClassName('btn-primary')[0].click();
count++;
}
}
}
<button class="btn-primary" onclick="clickme()">Click me</button>
Actually next() and previous() buttons are not working like they should be, means if second element is displayed by next button then then after clicking previous button the first element has to be shown but it starts from the end .
One more problem is that after using setTimeout() function, when i click on next it accelerate the speed of timer as it should have same speed for auto play which is given.
var newsArr = ["my name is nouman", "i live in abbottabad", "the breaking news about Pakistan"];
var i = 1;
var x = document.getElementById("demo");
function next() {
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
i++;
} else {
i = 0;
x.innerHTML = newsArr[i];
}
setTimeout(next, 2000);
}
function prev() {
if (i >= 0) {
x.innerHTML = newsArr[i];
i--;
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
}
}
<div class="newsslider">
<p class="text" id="demo">my name is nouman </p>
<button class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
<button class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>
As far as I can guess what you want:
Every time you call the next function a new timeout start. Means that if you click on next for 3 times. You will have 3 timeouts running at the same time. That's way you see it accelerate.
The solution is to clear the running timeout before to set a new one. This way you will always have at most one timeout running.
Also you might wanna first update the index and then adjust it if not valid. Otherwise you might end up in weird situations where you have i > arr.length.
var newsArr = [
"my name is nouman",
"i live in abbottabad",
"the breaking news about Pakistan",
];
var i = 0;
var x = document.getElementById("demo");
var timeoutId;
function next() {
if (timeoutId) {
clearTimeout(timeoutId);
}
i++;
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
} else {
i = 0;
x.innerHTML = newsArr[i];
}
timeoutId = setTimeout(next, 2000);
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = newsArr[i];
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
}
}
<div class="newsslider">
<p class="text" id="demo">my name is nouman </p>
<button class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
<button class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>
i would like to ask all , i am face with issue that i want to blink three html links when user clicks on the button with specific time
<a id="tip1">blink1</a>
<a id="tip2">blink2</a>
<a id="tip3">blink3</a>
<input type="button" value="CLICK ME" id="btn" />
$("#btn").click(function () {
doBlink(900);
});
function doBlink(900)
{
set blink for $("#tip1") is 300, after finishing for blinking one, we will call for blink2..etc..
}
Thanks in advance
Here is a Fiddle Demo that will do this:
$("#btn").click(function () {
doBlink(900);
});
function doBlink(value) {
var time = value/3;
blink(1, time);
}
function blink(id, time) {
var counter = 0;
var interval = setInterval(function () {
$("#tip" + id).toggleClass('blinked');
counter += 50;
if (counter >= time && id < 4) {
clearInterval(interval);
id++;
blink(id, time);
}
}, 100);
}
<!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
I want implement timer using java script.I want to decrement timer with variation of interval.
Example.Suppose my timer starts at 500 .
I want decrement timer depending on the level such as
1. 1st level timer should decrement by 1 also decrement speed should be slow.
2.2nd level timer should decrement by 2 and decrement speed should be medium
3.3rd level timer should decrement by 3 and decrement speed should be fast
I can create timer using following code:
<script type="text/javascript">
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time)
{
TotalSeconds=Time;
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer();
setTimeout("Tick()", 1000);
}
function Tick() {
TotalSeconds -= 10;
if (TotalSeconds>=1)
{
UpdateTimer();
setTimeout("Tick()", 1000);
}
else
{
alert(" Time out ");
TotalSeconds=1;
Timer.innerHTML = 1;
}
}
But i call this CreateTimer() function many times so its speed is not controlling because i call it many times.
Couple of points:
You've used all global variables, it's better to keep them private so other functions don't mess with them
Function names starting with a captial letter are, by convention, reserved for constructors
The function assigned to setTimeout doesn't have any public variables or functions to modify the speed while it's running so you can only use global variables to control the speed. That's OK if you don't care about others messing with them, but better to keep them private
The code for UpdateTimer hasn't been included
Instead of passing a string to setTimeout, pass a function reference: setTimeout(Tick, 1000);
Anyhow, if you want a simple timer that you can change the speed of:
<script>
var timer = (function() {
var basePeriod = 1000;
var currentSpeed = 1;
var timerElement;
var timeoutRef;
var count = 0;
return {
start : function(speed, id) {
if (speed >= 0) {
currentSpeed = speed;
}
if (id) {
timerElement = document.getElementById(id);
}
timer.run();
},
run: function() {
if (timeoutRef) clearInterval(timeoutRef);
if (timerElement) {
timerElement.innerHTML = count;
}
if (currentSpeed) {
timeoutRef = setTimeout(timer.run, basePeriod/currentSpeed);
}
++count;
},
setSpeed: function(speed) {
currentSpeed = +speed;
timer.run();
}
}
}());
window.onload = function(){timer.start(10, 'timer');};
</script>
<div id="timer"></div>
<input id="i0">
<button onclick="
timer.setSpeed(document.getElementById('i0').value);
">Set new speed</button>
It keeps all its variables in closures so only the function can modify them. You can pause it by setting a speed of zero.
Hope, this could be helpful:
<html>
<head>
<script type="text/javascript">
function showAlert()
{
var t=setTimeout("alertMsg()",5000);
}
function alertMsg()
{
alert("Time up!!!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Start" onClick="timeMsg()" />
</form>
</body>
</html>
Check this demo on jsFiddle.net.
HTML
<div id="divTimer">100</div>
<div id="divDec">1</div>
<div id="divSpeed">100</div>
<input id="start" value=" Start " onclick="javaScript:start();" type="button" />
<input id="stop" value=" Stop " onclick="javaScript:stop();" type="button" /><br/>
<input id="inc" value=" Increase " onclick="javaScript:increase();" type="button" />
<input id="dec" value=" Decrease " type="button" onclick="javaScript:decrease();"/>
JavaScript
var handler;
function start() {
handler = setInterval("decrementValue()", parseInt(document.getElementById('divSpeed').innerHTML, 10));
}
function stop() {
clearInterval(handler);
}
function decrementValue() {
document.getElementById('divTimer').innerHTML = parseInt(document.getElementById('divTimer').innerHTML, 10) - parseInt(document.getElementById('divDec').innerHTML, 10);
}
function increase() {
document.getElementById('divDec').innerHTML = parseInt(document.getElementById('divDec').innerHTML, 10) + 1;
document.getElementById('divSpeed').innerHTML = parseInt(document.getElementById('divSpeed').innerHTML, 10) + 200;
stop();
decrementValue();
start();
}
function decrease() {
document.getElementById('divDec').innerHTML = parseInt(document.getElementById('divDec').innerHTML, 10) - 1;
document.getElementById('divSpeed').innerHTML = parseInt(document.getElementById('divSpeed').innerHTML, 10) - 200;
stop();
decrementValue();
start();
}
Hope this is what you are looking for.