How can i stop my animation circle ? - JS - javascript

i'm doing a game with javascript only using function, i know it's not the best method but i'm still learning prototypes before steping in to use them. So, to the point, i have a request animatation frame that calls him self so my function keep executing. The problem is when the player dies i want to stop the enemys to be created , basicaly, stop the functions execution. Better show you some code.
This is my animation function:
function animate() {
if (endGame() == true) {
return;
}
requestAnimationFrame(animate);
if(theBird == null && canContinue == true) {
theBird = getBird(); // variavel com a div do bird
setTimeout(createDrake(), Math.round(Math.random() * 800));
setTimeout(createBrick(), Math.round(Math.random() * 3000));
setTimeout(createBoss(), Math.round(1000 + Math.random() * 15000));
setTimeout(createPowerUp(), Math.round(Math.random() * 15000));
document.addEventListener('keydown', onKeyPressed);
document.addEventListener('keyup', onKeyReleased);
}
else {
updateBirdLocation();
updateBirdSpeed();
flyDrakes();
flyBrick();
flyBullets();
flyPowerUp();
flyBoss();
checkBulletCollisions();
checkBulletCollisionsBricks()
checkShipCollision();
checkShipCollisionBricks();
checkShipCollisionBonusP();
checkShipCollisionBoss();
checkBulletCollisionsBoss();
updateScores();
checkEnemyBulletCollisions();
MoveArrayX(bullets2, -10);
MoveArrayX(bullets3, -10);
removePassingElements();
}
}
And this one is my function stopGame that is beeing called everytime player looses:
function endGame() {
Rbutton.style.visibility= "visible";
var RestartDiv = document.createElement("div");
RestartDiv.id = "RestartDiv";
gameDiv.appendChild(RestartDiv);
document.getElementById('RestartDiv').innerHTML += "You scored" + " " + mobHits + " " + "points!";
canContinue = false;
return true;
}
My attemp to stop this was the 1st part of animate :
function animate() {
if (endGame() == true) {
return;
}
but if i do this my game stops ( like i want ) but before the player dies.
I do not have endGame beeing executed anywhere besides the functions where the player dies. How can i solve this ?
Thank you
EDIT: This is an example how i detect a player died:
function checkShipCollisionBoss() {
for (var k=0; k<bossArray.length; k++) {
if ((isCollide(BirdsDiv, bossArray[k]) ) == true){
endGame();
}
}
}
isCollide is a function that detects the collision.

Then do like this,
function endGame() {
if(isCollide()) // return a boolean from this function
{
Rbutton.style.visibility= "visible";
var RestartDiv = document.createElement("div");
RestartDiv.id = "RestartDiv";
gameDiv.appendChild(RestartDiv);
document.getElementById('RestartDiv').innerHTML += "You scored" + " " + mobHits + " " + "points!";
canContinue = false;
return true;
}
return false;
}
Also remember this, if you are going to check a boolean you can simple give
if(true) or if (false)
Example,
var bool = true;
if(bool)
// your stuff

Your endGame function always return true, so endGame() == true
Then in animate function:
function animate() {
if (endGame() == true) {
return;
}
...
}
which is:
function animate() {
if (true == true) {
return;
}
...
}
which is:
function animate() {
if (true) {
return;
}
...
}
which is:
function animate() {
return;
...
}
So it always return

Related

Javascript beginner question: Bool or Int?

I'm a Javascript beginner and I want to ask why a thing is happening in my code
var whoisplaying = 2;
function laX(lid) {
if (whoisplaying == 2) {
document.getElementById(lid).textContent = "X";
minus();
} else {
prompt("hi");
plus();
}
}
function minus() {
whoisplaying = 1;
}
function plus() {
whoisplaying = 2;
}
On this one above I have no issues on the on click function applied to a few buttons, while if I set the var whosiplaying as a bool as im gonna show in the next snippet, it doesnt work: the else statment will never be working, the var will always be true.
var whoisplaying = true;
function laX(lid) {
if (whoisplaying == true) {
document.getElementById(lid).textContent = "X";
minus();
} else {
prompt("hi");
plus();
}
}
function minus() {
whoisplaying = false;
}
function plus() {
whoisplaying = true;
}
Can someone explain me why, so I'll not make mistakes in the future? Thanks you.
Here are the two examples of yours, they behave the same way!, note that if(whoisplaying == true) could just be if(whoisplaying) when you check against booleans
Using Numbers
var whoisplaying = 2;
function laX() {
if(whoisplaying == 2) {
document.getElementById("lid").textContent="X";
minus();
}else {
prompt("hi");
plus();
}
}
function minus() {
whoisplaying = 1;
}
function plus() {
whoisplaying = 2;
}
<p id="lid"></p>
<button onclick="laX()">Click me</button>
Using Booleans
var whoisplaying = true;
function laX() {
if(whoisplaying == true) {
document.getElementById("lid").textContent="X";
minus();
}else {
prompt("hi");
plus();
}
}
function minus() {
whoisplaying = false;
}
function plus() {
whoisplaying = true;
}
<p id="lid"></p>
<button onclick="laX()">Click me</button>
Ok since you have added a comment that says
Don't ask me why but using boolenas it wasn't working when I tried it before... the else statement wasn't working...now it works both way.
I realised that the mistake was a typo in your code, I think you have typed = instead of == in your if statement although the given code doesn't have that typo, so that makes the if statement assign the true value each time to that variable and the returned value from that expression is truthy so the else never executes, but always the body of the if statement executes, here is an example
<p id="lid"></p>
<button onclick="laX()">Click me</button>
Using Booleans
var whoisplaying = true;
function laX() {
if(whoisplaying = true) {
document.getElementById("lid").textContent="X";
minus();
}else {
prompt("hi");
plus();
}
}
function minus() {
whoisplaying = false;
}
function plus() {
whoisplaying = true;
}
<p id="lid"></p>
<button onclick="laX()">Click me</button>

Stop recursive setTimeout function

Im running a recursive setTimeout function and I can run it many times, it has a clearTimeout, with this property I can handle how to stop the function running.
But I can't figure out how to stop it in another function.
var a = 0;
var b = 0;
function Listener(x, y) {
var lValue = y == true ? a : b;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
setTimeout(Listener.bind(this, x, y), 1000);
} else {
clearTimeout(Listener);
if(y == true){
a=0;
}else{
b=0;
}
}
}
When i tried to run it twice, it works:
My doubt is: How can I stop a particular running instance.
A couple notes:
Given the constant timeout of 1000, you should be using setInterval() instead. It will greatly simplify your function, and allow you to cancel the interval whenever you want.
Using global variables is code smell, create an object instead to hold a reference to the value being incremented. Doing so will also allow your function parameters to be more intuitive.
Here's a solution incorporating these two suggestions:
function range (step, start = 0, stop = 100) {
const state = {
value: start,
interval: setInterval(callback, 1000)
};
function callback () {
if (state.value < stop) {
console.log(state.value);
state.value += step;
} else {
console.log('timer done');
clearInterval(state.interval);
}
}
callback();
return state;
}
const timer1 = range(10);
const timer2 = range(20);
setTimeout(() => {
console.log('stopping timer 1');
clearInterval(timer1.interval);
}, 2500);
setTimeout(() => {
console.log('timer 2 value:', timer2.value);
}, 3500);
You could elevate the timer to a higher scope that is accessible by other functions.
var a = 0;
var b = 0;
var timer = null;
function Listener(x, y) {
var lValue = y == true ? a : b;
if (lValue < 100) {
console.log(lValue);
if (y == true) {
a += x;
} else {
b += x;
}
timer = setTimeout(Listener.bind(this, x, y), 1000);
} else {
clearTimeout(timer);
if (y == true) {
a = 0;
} else {
b = 0;
}
}
}
function clearTimer() {
if (timer !== null) clearTimeout(timer);
}
Listener(3, 3);
// clear the timer after 3 secnods
setTimeout(clearTimer, 3000);
create a variable and store the reference of setTimout on that variable, after that you just clearTimout with that variable reference
e.x
GLOBAL VARIABLE:
var k = setTimeout(() => { alert(1)}, 10000)
clearTimeout(k)
var a = 0;
var b = 0;
var recursiveFunctionTimeout = null;
function Listener(x, y) {
var lValue = y == true ? a : b;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
recursiveFunctionTimeout = setTimeout(Listener.bind(this, x, y), 10);
} else {
clearTimeout(recursiveFunctionTimeout);
if(y == true){
a=0;
}else{
b=0;
}
}
}
LOCAL VARIABLE:
var a = 0;
var b = 0;
function Listener(x, y) {
var lValue = y == true ? a : b;
var recursiveFunctionTimeout = null;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
recursiveFunctionTimeout = setTimeout(Listener.bind(this, x, y), 10);
} else {
clearTimeout(recursiveFunctionTimeout);
if(y == true){
a=0;
}else{
b=0;
}
}
}

Want JavaScript script to run when the Div is in the viewport

I want to run a JS script when a particular div comes into the viewport/is visible.
The div will always be visible, but when the user scrolls it in to view.
I have created a JSFiddle with the example:
Example http://jsfiddle.net/sv8boe9u/21/
JS
consoleText(['HELLO,', 'HERE IS A BIT ABOUT ME,', 'ENJOY!'], 'text', ['#333', '#333', '#333']);
function consoleText(words, id, colors) {
"use strict";
if (colors === undefined) {
colors = ['#fff'];
}
var visible = true;
var con = document.getElementById('console');
var letterCount = 1;
var x = 1;
var waiting = false;
var target = document.getElementById(id);
target.setAttribute('style', 'color:' + colors[0]);
window.setInterval(function() {
if (letterCount === 0 && waiting === false) {
waiting = true;
target.innerHTML = words[0].substring(0, letterCount);
window.setTimeout(function() {
var usedColor = colors.shift();
colors.push(usedColor);
var usedWord = words.shift();
words.push(usedWord);
x = 1;
target.setAttribute('style', 'color:' + colors[0]);
letterCount += x;
waiting = false;
}, 1000);
} else if (letterCount === words[0].length + 1 && waiting === false) {
waiting = true;
window.setTimeout(function() {
x = -1;
letterCount += x;
waiting = false;
}, 1000);
} else if (waiting === false) {
target.innerHTML = words[0].substring(0, letterCount);
letterCount += x;
}
}, 120);
window.setInterval(function() {
if (visible === true) {
con.className = 'console-underscore hidden';
visible = false;
} else {
con.className = 'console-underscore';
visible = true;
}
}, 400);
}
To clarify, I want it to start at 'Hello' when it is actually in viewport. Any ideas?
Thanks.
Using the jQuery scroll() and scrollTop() functions you can specify a height in px that triggers another function when reached such as:
$(window).scroll(function () {
if ($(this).scrollTop() >= 50) { // If page is scrolled more than 50px
doSomething(); // call this function
}
});
jQuery Scroll and Scroll Top
you can use the scroll function ..like create a function that runs until wen you reach that element u are targeting.. then call the alert('hello');
window.addEventListener('scroll', (e) => {
console.log(window.scrollY)
if (window.scrollY == 705) {
alert('got ya')
// do your stuff here boss
}
})
you should make sure to find that scroll position wen yo element comes into view and then put it wr 705 is.. hope this helps ya

trying to make a timer stop when the user reaches the bottom of the page using jQuery

I have a timer that starts counting up when the page is loaded. I want it to stop when the user scrolls to the bottom of the page. Here is the jQuery I've written:
function timerTick(time, stop)
{
if(stop == false)
{
setInterval(function ()
{
time += 1;
var displayTime = time/10;
if(displayTime % 1 != 0)
{
$('.time').text(displayTime.toString());
}
else
{
$('.time').text(displayTime.toString() + ".0");
}
}, 100);
}
else //behavior is the same if i remove the else block
{
return;
}
}
$(document).ready(function () {
var time = 0;
var stop = false;
timerTick(time, stop);
//check if we're at the bottom
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
stop = true;
}
});
});
The timer counts up perfectly, the problem is I can't get it to stop. If I replace the stop = true; line with alert('abc');, the alert shows up when the user reaches the bottom. So all of the pieces are working, just for some reason setting stop to true doesn't stop the timerTick function from going into the if(stop == false) block.
Can someone tell me what I'm doing wrong?
Edit: I made a jsFiddle.
You have to clear interval as soos as user reach the end of page. Otherwise it will continue executing.
Try:
var intervalId;
function timerTick(time, stop)
{
if(stop == false)
{
intervalId=setInterval(function () //Set the interval in a var
{
time += 1;
var displayTime = time/10;
if(displayTime % 1 != 0)
{
$('.time').text(displayTime.toString());
}
else
{
$('.time').text(displayTime.toString() + ".0");
}
}, 100);
}
else //behavior is the same if i remove the else block
{
return;
}
}
$(document).ready(function () {
var time = 0;
var stop = false;
timerTick(time, stop);
//check if we're at the bottom
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
stop = true;
clearInterval(intervalId);//HERE clear the interval
}
});
});
DEMO
to determine bottom of the page you could try this
if(window.innerHeight + document.body.scrollTop >= document.body.offsetHeight) {
stop = true;
}
Update:
you need to make your variable stop global, declare it outside of documnet.ready function.
setInterval function returns number that you can later pass into clearInterval to stop the timer.
Declare
var Timeout=0;
check
if(stop == false)
inside the setInterval function
like
Timeout=setInterval(function ()
{
if(stop == false)
{
time += 1;
var displayTime = time/10;
if(displayTime % 1 != 0)
{
$('.time').text(displayTime.toString());
}
else
{
$('.time').text(displayTime.toString() + ".0");
}
}
else
{
clearInterval(Timeout);
}
}, 100);

Finding the direction of scroll using setTimeout

on a onscroll command I have a function which checks the scroll position and then waits 200ms and then checks it again, even tho' I have put the if function to stop it repeating the function the alert tells me that the xy[1] and ye are the same.
function dothescroll() {
if (scrolling == false) {
scrolling = true;
var xy = getScrollXY();
var ye = xy[1];
setTimeout(function(){
alert(xy[1] + " + " + ye);
if (xy[1] > ye) {
scrollup();
} else {
scrolldown();
}
},200);
}
}
Any ideas??
Thankss.x
You need to call getScrollXY() again to get the new coordinates:
setTimeout(function(){
xy = getScrollXY();
alert(xy[1] + " + " + ye);
if (xy[1] > ye) {
scrollup();
} else {
scrolldown();
}
},200);

Categories

Resources