Prevent setInterval() from increasing speed after set number of clicks - javascript

I'm building a clicker game where I want a timer to auto click for me. I want the timer to increase speed each time I click a button, but prevent increasing the timer's speed after clicking said button 5 times.
This is what I have come up with so far:
var total = 0;
var itemValue = 0;
var autoClick = function() {
if(itemValue <= 5) {
total = total + itemValue;
}
};
$("#button").click(function() {
itemValue++;
setInterval(autoClick, 1000);
});
Any suggestions?

So you want to increase total by x value each second.
x depending on how namy clicks on an "increase speed button"...
I got it?
To prevent concurring intervals, you have to clear the previous.
var total = 0;
var itemValue = 0;
var myInterval;
var autoClick = function() {
total = total + itemValue;
console.log(total);
};
$("#button").click(function() {
if(itemValue <= 4) {
// Increase...
itemValue++;
// Prevents multiple intervals.
clearInterval(myInterval);
myInterval = setInterval(autoClick, 1000/itemValue);
console.log("Increasing by "+itemValue+" now...");
}else{
console.log("Hey! By "+itemValue+" is way enought!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Increase speed!</button>

Related

timer starts automatically instead of on a button press in javascript

I'm quite new to javascript so the answer is probably quite easy but anyways
I'm trying to make a simple click speed test but i cant get the timer to start when the user presses the click me button, so i resorted to just starting it automatically. if anyone can help me to start it on the button press it will be much appreciated
HTML code:
<button id="click2" onclick="click2()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="10stimer">10s</span>
JS code:
var click = document.getElementById("click2");
var amount = 0;
var seconds = 10;
var endOfTimer = setInterval(click2, 1000);
function click2() {
seconds--;
document.getElementById("10stimer").innerHTML = seconds + "s";
if (seconds <= 0) {
var cps = Number(amount) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("click2").disabled = true;
document.getElementById("10stimer").innerHTML = "Ended";
clearInterval(seconds);
}
}
document.getElementById("click2").onclick = function() {
amount++;
document.getElementById("clicksamount").innerHTML = amount + " Clicks";
}
It looks like you're overwriting your onclick function on the button with id click2 with the lowest 4 lines.
Also, you call clearInterval() with the seconds variable instead of the actual interval, which is referenced by endOfTimer.
I'd suggest to have a separated timer management in a function which you call only on the first click of your button.
See JSFiddle
<button id="clickbutton" onclick="buttonClick()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="secondcount">10s</span>
// We will have timerStarted to see if the timer was started once,
// regardless if it's still running or has already ended. Otherwise
// we would directly restart the timer with another click after the
// previous timer has ended.
// timerRunning only indicates wether the timer is currently running or not.
var timerStarted = false;
var timerRunning = false;
var seconds = 10;
var clickAmount = 0;
var timer;
function buttonClick() {
if (!timerStarted) {
startTimer();
}
// Only count up while the timer is running.
// The button is being disabled at the end, therefore this logic is only nice-to-have.
if (timerRunning) {
clickAmount++;
document.getElementById("clicksamount").innerHTML = clickAmount + " Clicks";
}
}
function startTimer() {
timerStarted = true;
timerRunning = true;
timer = setInterval(timerTick,1000);
}
function timerTick() {
seconds--;
document.getElementById("secondcount").innerHTML = seconds + "s";
if (seconds <= 0) {
timerRunning = false;
clearInterval(timer);
var cps = Number(clickAmount) / 10;
document.getElementById("clickbutton").disabled = true;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS (" + clickAmount + "clicks in total)!";
}
}
I made some changes to your code. Effectively, when the user clicks the first time, you start the timer then. The timer variables is null until the first the user clicks.
var click = document.getElementById("click2");
var noOfClicks = 0;
var seconds = 10;
var timer = null;
function doTick(){
seconds--;
if(seconds<=0){
seconds = 10;
clearInterval(timer);
document.getElementById("10stimer").innerHTML= "Ended"
timer=null;
document.getElementById("click2").disabled = true;
}
updateDisplay()
}
function updateClicks(){
if(!timer){
timer=setInterval(doTick, 1000);
clicks= 0;
seconds = 10;
}
noOfClicks++;
updateDisplay();
}
function updateDisplay(){
var cps = Number(noOfClicks) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("10stimer").innerHTML =seconds;
}
click.addEventListener('click', updateClicks)
https://jsbin.com/bibuzadasu/1/edit?html,js,console,output
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
Use event listeners rather than onclicks
usage example:
HTML
<button id="mybutton">Click me!</button>
JS
/* ABOVE CODE ... */
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
<button id="mybutton">Click me!</button>
//state initialization
var amount = 0;
var seconds = 10;
var timedOut=false;
var timerId=-1;
//counters display
var clicksDisplay= document.getElementById("clicksamount");
var timerDisplay= document.getElementById("10stimer");
function click2(e){
//first click
if(timerId===-1){
//start timer
timed();
}
//still in time to count clicks
if(!timedOut){
amount++;
clicksDisplay.innerText=amount +" Clicks";
}
}
function timed(){
//refresh timer dispaly
timerDisplay.innerText=seconds+"s";
seconds--;
if(seconds<0){
//stop click count
timedOut=true;
}else{
//new timerId
timerId=setTimeout(timed,1000);
}
}

Converting a manual slideshow to automatic

I followed a tutorial and created a simple manual loop slideshow. I'm trying to make it so it changes the slide automatically even if the prev/next buttons aren't clicked. I tried a crude approach by setting a delay between automatic click events on the "next" button but for some reason it clicks it only once and stops. My js knowledge is very limited and can't figure it out, any input is appreciated. This is the script so far:
$(function() {
var ul = $(".slider ul");
var slide_count = ul.children().length;
var slide_width_pc = 100.0 / slide_count;
var slide_index = 0;
var first_slide = ul.find("li:first-child");
var last_slide = ul.find("li:last-child");
last_slide.clone().prependTo(ul);
first_slide.clone().appendTo(ul);
ul.find("li").each(function(indx) {
var left_percent = (slide_width_pc * indx) + "%";
$(this).css({"left":left_percent});
$(this).css({width:(100 / slide_count) + "%"});
});
ul.css("margin-left", "-100%");
$(".slider .prev").click(function() {
console.log("prev button clicked");
slide(slide_index - 1);
});
$(".slider .next").click(function() {
console.log("next button clicked");
slide(slide_index + 1);
});
function slide(new_slide_index) {
var margin_left_pc = (new_slide_index * (-100) - 100) + "%";
ul.animate({"margin-left": margin_left_pc}, 400, function() {
if(new_slide_index < 0) {
ul.css("margin-left", ((slide_count) * (-100)) + "%");
new_slide_index = slide_count - 1;
}
else if(new_slide_index >= slide_count) {
ul.css("margin-left", "-100%");
new_slide_index = 0;
}
slide_index = new_slide_index
});
}
});
Here is an approach to make it sliding automatically...
But if user clicks on prev/next, it holds the automatic feature for a defined "idle" time.
It need two lines added to your click handlers:
var autoEnabled = true; // ADDED
$(".slider .prev").click(function() {
console.log("prev button clicked");
slide(slide_index - 1);
autoEnabled = false; // ADDED
disabledCount = 0; // ADDED
});
$(".slider .next").click(function() {
console.log("next button clicked");
slide(slide_index + 1);
autoEnabled = false; // ADDED
disabledCount = 0; // ADDED
});
And this to cyclically slide or check if it can re-enable itself.
// ----------------- Automatic sliding interval with "idle time" to re-enable on user click
var idleTime = 5000; // Time without manual click to re-enable automatic sliding.
var autoSlideDelay = 1000; // Time between each slide when automatic.
var disabledCount = 0;
var autoSlide = setInterval(function(){
if(autoEnabled || disabledCount >= idleTime/autoSlideDelay ){
disabledCount = 0;
autoEnabled = true;
slide(slide_index + 1);
}else{
disabledCount++;
}
},autoSlideDelay);
var break_auto_slide = false;
function auto_silde()
{
if(break_auto_slide)
{
break_auto_slide = false;
return;
}
slide(slide_index + 1);
setTimeout(auto_silde,1000 /* time in ms*/);
}
setTimeout will call the function in a specified timeout in milliseconds.
Variable break_auto_slide - set it to true to stop the automatic slide. Next time the function is called it will return without setting a new timer and will reset this variable so auto mode can be turned on again.

How to change amount variable is incremented by in JavaScript?

!NO JQUERY!
Ok, so I am making a game for my friends based on cookie clicker game from years ago and my issue is I want to increase what the clicks are incremented by when I click a multiplier button.
Basically, when the user reaches 100 clicks and if they click on the multiplier button it will increase the increment by 1.
The cpcm function function cpcm(){cl1ck5m = 1;} will increase cl1ck5m by 1 when the user clicks the multiplier button. I want to add this value to the main increment total = cl1ck +=1; in the function cl1ckm8() {} only if the user clicks the multiplier button when they reach 100 clicks.
I dont know how I would do this.
var cl1ck5 = 0;
var total = 0;
var cl1ck5m = 0;
var rotated = false;
window.alert("H3lp C00ki3 Man3st3r!\nCan y0u h3lp C00ki3 Man3st3r c0ll3ct c00ki3s?");
function cl1ckm8() {
total = cl1ck +=1;
document.getElementById('cl1ckC0unt').innerHTML = total;
if (cl1ck5 == 90) {
var div = document.getElementById('butt');
var deg = rotated ? 0 : 90;
var msg = document.getElementById("ache");
msg.innerHTML = "nineD d3gr33s";
div.style.transform = 'rotate('+deg+'deg)';
}
if (cl1ck5 == 100) {
var div = document.getElementById('cpcbutt');
div.innerHTML = "1";
}
}
function cpcm(){
cl1ck5m = 1;
}
I'm not sure what you're asking but anyway...
var multiplierButtonClicked = false;
document.getElementById("multiplier").onclick = function(){
if (cl1ck5 >= 100)
multiplierButtonClicked=true;
}
function cl1ckm8()
{
total = cl1ck +=1;
if (multiplierButtonClicked)
total += cl1ck5m;
//...
}
function cpcm(){
if (multiplierButtonClicked)
cl1ck5m += 1;
}
I fixed it. Thanks for any help.
I simply put the multiplier in place of the 1 in total = cl1ck +=1; like total = cl1ck +=cl1ckm;. I was trying to avoid this way to find other ways of doing it but this works best.

Javascript count up onload load function

I am creating a script which will refresh "viewers" count displayed at the top of my website.
Javascript:
<script type="text/javascript">
window.onload = function(){
var auto_refresh = setInterval(
function ()
{
$('#viewers').load('viewers.php');
}, 5000);
}
</script>
HTML:
<span id="viewers">0</span>
viewers.php output:
100
I'd like to add a "count up/down" effect, so for example if the viewers.php outputs 200, it will then count up after the 5000 milliseconds, and if this count dropped to 50, the 100 will count down to 50.
Thanks for the help!
Here is a solution that counts up or down to the new number of viewers over a given delay period. It seems to run a little slow, probably due to the delay of my code inside the setInterval.
Just call the setViewers whenever you want to update the count.
<script type="text/javascript">
window.onload = function(){
var delay = 4000;
var viewers = $("#viewers");
var auto_refresh = setInterval(
function ()
{
var curViewers = Number(viewers.html())
$('#viewers').load('viewers.php', function(){
var newViewers = Number(viewers.html());
setViewers(curViewers, newViewers);
});
}, 5000);
function setViewers(currentNum, newNum){
if(currentNum == newNum) return;
var updateSpeed = delay / Math.abs(currentNum - newNum);
var countDir = currentNum > newNum ? -1 : 1;
var timer = setInterval(function(){
currentNum += countDir;
viewers.text(currentNum);
if(currentNum == newNum) clearInterval(timer);
}, updateSpeed);
}
}
</script>

Can you count clicks on a certain frame in an animation in javascript?

I'm looking to build a very simple whack a mole-esque game in javascript. Right now I know how to do everything else except the scoring. My current animation code is as follows
<script language="JavaScript"
type="text/javascript">
var urls;
function animate(pos) {
pos %= urls.length;
document.images["animation"].src=urls[pos];
window.setTimeout("animate(" + (pos + 1) + ");",
500);
}
window.onload = function() {
urls = new Array(
"Frame1.jpg","Frame2.jpg"
);
animate(0);
}
</script>
So far it all works, the first frame is the hole and the second is the groundhog/mole out of the hole. I need to count the clicks on the second frame but I can't figure out how to incorporate a counter. Help? (Sorry if the code doesn't show up correctly, first time using this site)
Here is an example that counts clicks on the flashing animation: http://jsfiddle.net/maniator/TQqJ8/
JS:
function animate(pos) {
pos %= urls.length;
var animation = document.getElementById('animation');
var counter = document.getElementById('counter');
animation.src = urls[pos];
animation.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
setTimeout(function() {
animate(++pos);
}, 500);
}
UPDATE:
Here is a fiddle that only detects click on one of the images: http://jsfiddle.net/maniator/TQqJ8/8/

Categories