Clearing Timeout After Button Clicked - javascript

I'm currently trying to code something similar to tamagotchi "care mistakes".
In this case, I'm trying to create a function which checks if the object's hunger stat is above or at 10. Once this occurs, a timer will start, and if it remains above 10 after 10 seconds, it'll be logged as a "mistake".
However, if the user does another action which reduces the hunger below 10, it'll clear the timer.
I'm unable to get the timer to clear properly at the moment despite trying the code below.
var changeHungerMood = setInterval(mistakeCheck, 5000);
function mistakeCheck() {
var mistakeTimer
function addMistake() {
stats.mistakes += 1;
}
if (stats.hunger >= 10) {
var mistakeTimer = setTimeout(addMistake, 10000);
} else {
clearTimeout(mistakeTimer);
console.log("Mistake Cleared!");
}
}
minmaxHunger("hunger", 10, 0);
At the moment, even if hunger goes below 10 after the check, the timer isn't cleared and it's still logged as a mistake. Could anyone please help? Thank you.

You should clarify what you need to accomplish in each case.
Very imperatively, you need:
To set your timer if stats.hunger >= 10, you're doing it well (except that you declare mistakeTimer with var two times... skip the second var).
When the 10 seconds are over, instead of calling addMistake, you need to check if stats.hungeris still 10 or more, and if it's the case, call your addMistake function.
So you need to add a function addMistakeIfNeeded that do the check and call addMistake if needed. And your timer should call this addMistakeIfNeeded function instead of addMistake.
And #Jonas is right, you need to put addMistake and addMistakeIfNeeded out of the mistakeCheck function.

Related

How can I check a variables value constantly without using setInterval?

I am building a incremental game. I have a progress bar that fills up 1 point every second.. And when that bar reaches 10 points it resets back to 0..
The problem I am having is checking if the variable is 10 at all times. I am currently using setInterval to run the function every 10 milliseconds but I feel like this is not good for the website.
I have been trying to find a solution for this for months, can someone please help me out here..
In short: How do I check a variables value at all times without causing lag/inefficiency
So, to recap, you're running a setInterval at 10ms which task is just to check if the value of some variable equals 10. There's so many solutions, but hard to answer specifically without seeing any code.
Solution 1: Call a desired function immediately after where you increment your variable
const doTheMagic = (points) => {
console.log(`You reached score: ${points}`)
};
let points = 0; // Start at 0
const incrementPoint = () => {
points += 1;
if (points === 10) doTheMagic(points);
points %= 10; // Loop-back points to 0 when reaches 10
};
// You say you increment `points` at intervals of ~1000ms:
setInterval(incrementPoint, 1000);
Wait 10s... Then again 10s... etc...
Solution 2: Use setter
Solution 3: Use Proxy

Why cant I scroll browser window in a loop in console?

I want to scroll down the browser window in a loop in console. I want it so that every time a scroll down (x)px down I stop, do something and then scroll (x)px again and then stop etc. until the page with ends (its a very long one, I want to parse info from it).
But when I started I stumbled upon an issue, that the scrolling function is executed only once, after the loop ends.
let i = 0;
scrollDownTillEnd = () => {
for(i; i<100; i++) {
window.scrollBy(0, 1000);
};
scrollDownTillEnd();
(it is a simplified example, but the idea should be clear)
I put the code in the console, being on a page I want to scroll, and get then the value of i at the end of the loop and only one scroll down.
Please, explain me, why this piece of code behaves like this and how to make it work, as I mentioned before (in every loop it scrolls a little bit).
Thank you!
Let me help address a few issues going on here.
1) You have an infinite loop going on because you are not checking that i is less than 100 even though you are incrementing it each time. You need to check that i < 100 so that the loop will eventually end. In your loop, 0 will always be less than 100 so the loop will never end.
2) You have a syntax error in your example because you're not actually closing out the scrollDownTillEnd function with a curly brace before calling the function itself.
3) Lastly, as good practice, you need to reset your i variable to 0 each time so that we can run this piece of code over and over again. The way you have it set up in your example, since i will be equal to 100 at the end of the first run, the loop won't ever run again after that until you reset i to 0 again. The easiest way to do this is to just initialize i to a value of 0 each time you execute this loop.
Try something like this:
scrollDownTillEnd = () => {
for(let i = 0; i < 100; i++) {
window.scrollBy(0, 1000);
};
};
scrollDownTillEnd();
You can use setInterval() since for loop will executes only once
function scrollDownTillEnd(countryDropdownList)
{
let scrollingInterval = setInterval(function(){
window.scrollBy(0,1000)
// write your condition
if (window.scrollHeight > 10000)
{
clearInterval(scrollingInterval)
}
},100)
}
scrollDownTillEnd();

How to make a very simple countdown timer in Javascript?

I'm making a simple game which generates random numbers and user has to enter a value, if users value matches the random value generated, the user wins basically this is a beginner project. I want to make a small counter so that user has a limited time to put in the value and I want that limited time to show on the screen in a label. Lets say that you have to put the value under 30 secs and the timer will count from 1 to 30 every second. The counting from 1 to 30 will update in the label every second. This is the logic I'm trying to work on right now and I can't figure out any other way... If I've done some mistake in code please comment or if you have much more simpler way please post it down below. (pls dont vote down im at threat of account suspension)
Heres the part of my timer code:
if(timer <= 30)
{
for(var i = 0;i >= 30;i++)
{
setInterval(null,1000);
timer++;
document.getElementById("counter").innerHTML = timer+" seconds wasted";
}
alert("Time is over, you lost by "+s);
}
You could create a recursive function.
Say var countDown function(){ time = time--;
setTimeout(countDown, 1000);}
Then you need a variable time that is accessible for the countDown function.
var time = 30;
In the countDown function you could create an updateTimeElement.
Try it out.
The setInterval function has 2 parameters, a callback (an anomynous function in javascript thats triggered) and the milliseconds between each trigger of the interval.
What you are doing in your script is making an interval with nothing to do each second (this runs indefinately), then increment the timer integer and updating the DOM. However, this all executes within seconds.
I'd suggest (before you use a function) you look at the documentation to see how you can improve your script to work as you intent to ;-) Here are a few links that might help you get started:
http://www.w3schools.com/js/js_timing.asp
https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/
I wont be doing the work for you, since this is a good exercise for a beginner programmer ;-)
If you can't figure it out, leave a comment below this answer and I'll get back to you to help you if you need further assistance.

Counting up using jquery

So far I have a little script that detects the scroll top position and at a set level I want it to trigger a jquery counter. So far I have an array with the maximum number inside var = eightyS = [3]; then there is..
if (y > 630) {
$('.targetS').each(function() {
//counter
delay(1000);
});
} else {
return false;
}
Now I've made something similar in C++ years ago (couldn't do it now with a gun to my head) so I followed a similar logic. But this is where I'm stuck. The idea behind this function is that it will do a read out on screen of 0 then 1 then 2 then 3. Any help is greatly appreciated
You could use a setInterval() which executes a function ever second such as below:
var count = 0;
var interval = setInterval(function(){
count++;
$('#counter').text(count);
}, 1000);
I've created a quick JSFiddle
You should be able to wrap this in to your code fairly easily. You may also want to use clearInterval(interval) to stop the function executing when you scroll back up the page; or when you get in to your else block, which would have the same effect. I've added a clearInterval() example to the JSFiddle on click of the stop link. You'll need to make sure the interval variable is in scope when clearing it.

window.setInterval possible scope issue?

Thanks for taking the time to read this post. Finally built up enough courage to ask a question here :) Hope I ask my question in the correct way.
My problem is that I am trying to randomly animate "squares" around a page but am having an issue with the setInterval method.
You can find it here http://jsfiddle.net/xEMXh/
In the Init function I am trying to go though each ghost element and set it a interval function that will then make it animate in a random direction every X seconds.
for (ghostCount = 0; ghostCount < ghosts.length; ghostCount += 1) {
var speed = LesMccutcheon.GhostHunter.GetSpeed($(ghosts[ghostCount]).attr('data-speed')),
activeGhost = ghosts[ghostCount];
window.setInterval(function() {
LesMccutcheon.GhostHunter.MoveInDirection(activeGhost);
}, speed);
}
What is happening is only the last "ghost" element is animating. I know this is because in the for loop I am overriding the variable and by the time the first interval is called activeGhost is the last set in the for loop.
I tried using ghosts[ghostCount] directly in the set.Interval but it seems set interval cannot access this. I tried setting it to a variable inside the set.Interval anom function but it logged as undefined.
My only other half baked idea is to try and set an incremental var identifier but that seems quite counter productive and not a good way to go.
Thanks in advance for any advice!
Les
in your code the variable activeGhost will be overwritten for each loop.
just put the calling of setInterval into a closure like this
( function (activeGhost) {
window.setInterval(function() {
LesMccutcheon.GhostHunter.MoveInDirection(activeGhost);
}, speed);
} ( activeGhost) );
this way the reference to the correct element should be kept.

Categories