I can't stop setInterval with clearInterval - javascript

Im creating simple slider for Mobile devices. It's all based on checking width and setInterval() method. The case is when the device width reaches above 800px I want it to stop ! To be honest Im not excatcly sure where to put clearInterval(). I tried it in resize event and it did not work too. The timer is still working and I can't stop it after its already triggered.
class mobileSlider {
constructor() {
this.image = document.querySelector(".mobile__top-slider");
this.topCircles = document.querySelector(".top__circles");
this.paths = ["xgarda.jpg", "logofinal.png", "my.jpg"];
this.initialWidth = window.innerWidth;
this.width = null;
this.timer = null;
this.isMobile = true;
this.createSlider();
}
createSlider() {
this.drawDots();
this.checkWidth();
this.animateSlider();
}
drawDots() {
this.paths.forEach((_, index) => {
const circle = document.createElement("div");
circle.setAttribute("class", "top circle");
circle.setAttribute("data-id", `${index + 1}`);
this.topCircles.appendChild(circle);
});
}
animateSlider() {
let currentIndex = 0;
this.image.style.backgroundImage = `url(./images/${this.paths[currentIndex]})`;
this.topCircles.children[currentIndex].style.border = "2px solid #322B0F";
if (this.isMobile) {
this.timer = setInterval(() => {
currentIndex++;
if (currentIndex > 2) {
currentIndex = 0;
this.topCircles.children[this.paths.length - 1].style.border = "none";
}
this.image.style.backgroundImage = `url(./images/${this.paths[currentIndex]})`;
this.topCircles.children[currentIndex].style.border =
"2px solid #322B0F";
if (currentIndex > 0) {
this.topCircles.children[currentIndex - 1].style.border = "none";
} else {
this.topCircles.children[currentIndex + 1].style.border = "none";
}
}, 2000);
} else if (!this.isMobile) {
console.log("przekroczony");
window.clearInterval(this.timer);
}
}
checkWidth() {
if (this.initialWidth >= 800) {
this.isMobile = false;
}
window.addEventListener("resize", () => {
if (window.innerWidth >= 800) {
this.isMobile = false;
this.animateSlider();
} else {
this.isMobile = true;
this.animateSlider();
}
});
}
}
const run = new mobileSlider();

Related

I do not know how to limit the time in between calling my function

//let screenWidth = window.screen.width;
//let screenHeight = window.screen.height;
let screenWidth = 800;
let screenHeight = 600;
let assets = {};
let frames = 60;
let score = 0;
let lives = 3;
let player;
// let enemie;
//let enemies;
let bullet;
//let bullets;
let powerup = 0;
let gameOver = true;
function drawScoreBoard() {
textSize(20);
fill('white');
text(`Score: ${score} / Lives: ${lives}`, 20, 40);
}
function preload() {
assets.player = loadImage('assets/Player.png');
assets.enemie = loadImage('assets/Enemie.png');
assets.bulletRight = loadImage('assets/Bullet_Right.png');
assets.bulletLeft = loadImage('assets/Bullet_Left.png');
assets.bulletUp = loadImage('assets/Bullet_Up.png');
assets.bulletDown = loadImage('assets/Bullet_Down.png');
}
function setup() {
bullets = createGroup();
enemies = createGroup();
assets.player.resize(30, 30);
assets.enemie.resize(30, 30);
assets.bulletRight.resize(30, 30);
assets.bulletLeft.resize(30, 30);
assets.bulletUp.resize(30, 30);
assets.bulletDown.resize(30, 30);
createCanvas(screenWidth, screenHeight);
}
function createBullet(){
let numList = [0, 90, 180, 270, 360];
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let randomdirection = numList[Math.floor(Math.random() * numList.length)];
let bullet = createSprite(bulletDirection[(Math.round(player.getDirection()/90))]);
enemie.centerX = random(0, screenWidth);
enemie.setSpeed(random(1,10));
enemie.setDirection(randomdirection);
enemie.setCollider("circle");
bullets.add(bullet);
}
function createPlayer(){
player = createSprite(assets.player);
player.bottom = screenHeight - 20;
player.centerX = screenWidth / 2;
}
function shoot(amountofbulletstobeshot) {
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let bullet = createSprite(bulletDirection[Math.abs(((Math.round(player.getDirection()/90))))]);
bullets.add(bullet);
// bullet.direction = player.direction;
bullet.centerX = player.centerX;
bullet.centerY = player.centerY;
bullet.setVelocity(11, player.getDirection());
// console.log('The players current direction right now is: ' + player.getDirection());
}
function shooting() {
if (keyIsDown(KEY.SPACE)) {
if (powerup === 1) {
shoot(3);
}
else {
shoot(1);
}
}
if (bullet) {
if (bullet.centerX[1] === screenWidth) {
bullets.remove(bullet);
}
}
}
function updateplayer() {
//movement
if (keyIsDown) {
if (keyIsDown(KEY.RIGHT_ARROW)) {
player.setVelocity(6, 0);
}
if (keyIsDown(KEY.LEFT_ARROW)) {
player.setVelocity(6, 180);
}
if (keyIsDown(KEY.UP_ARROW)) {
player.setVelocity(6, 270);
}
if (keyIsDown(KEY.DOWN_ARROW)) {
player.setVelocity(6, 90);
}
}
//dont go offscreen
if (player.left < 0) {
player.left = 0;
}
if (player.right > screenWidth) {
player.right = screenWidth;
}
if (player.top < 0) {
player.top = 0;
}
if (player.bottom > screenHeight) {
player.bottom = screenHeight;
}
enemies.overlap(player, HandlePlayerEnemieCollision);
//end up updateplayer
}
function updateEnemie() {
if (frameCount % 1 === 0) {
let directions = ["LEFT", "RIGHT", "UP", "DOWN"];
let direction = random(directions);
if (direction === "LEFT" && enemie.left > 0) {
enemie.centerX -= 5;
}
if (direction === "RIGHT" && enemie.right < screenWidth) {
enemie.centerX += 5;
}
if (direction === "UP" && enemie.top > 0) {
enemie.centerY -= 5;
}
if (direction === "DOWN" && enemie.bottom < screenHeight) {
enemie.centerY += 5;
}
}
}
function createEnemie() {
let directions = [270, 180, 0, 90];
direction = directions[(Math.floor(Math.random() * 5))];
enemies.overlap(bullets, HandleEnemieBulletCollision);
if (frameCount % 60 === 0) {
enemie = createSprite(assets.enemie);
enemie.centerX = Math.floor(Math.random() * 300) + 100;
enemie.centerY = Math.floor(Math.random() * 300) + 100;
enemie.setVelocity(Math.floor(Math.random() * 5) + 1, direction);
enemies.add(enemie);
}
}
function HandleEnemieEdgeCollision(enemie, edge) {
if (enemie.centerY === screenWidth) {
enemie.remove();
}
}
function HandleEnemieBulletCollision(enemie, bullet) {
enemie.remove();
bullet.remove();
score++;
}
function HandlePlayerEnemieCollision(player, enemie) {
enemie.remove();
player.remove();
lives--;
if (lives === 0) {
gameOver = true;
}
createPlayer();
}
/*
function updateEnemie() {
player.setVelocity(7, player.direction);
}
*/
function cheat() {
score = (score + 1000000);
lives = (lives + 1000000);
cheats = 'on';
if (cheats === 'on') {
textSize(50);
fill('yellow');
text('CHEATS ACTIVATED', 400, 300);
}
}
/*
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
*/
function drawGameOverScreen() {
background("black");
textAlign(CENTER);
fill("white");
textSize(40);
text("WELCOME", screenWidth/2, screenHeight/2);
textSize(20);
text("Press SPACE to play!", screenWidth/2, screenHeight/2 + 100);
if (keyWentDown(KEY.SPACE)){
resetGame();
gameOver = false;
}
}
function resetGame(){
score = 0;
lives = 3;
createPlayer();
}
function drawGame() {
background('lightgreen');
drawScoreBoard();
updateplayer();
drawSprites();
shooting();
// updateEnemie();
createEnemie();
}
function draw() {
if (gameOver === true) {
drawGameOverScreen();
} else {
drawGame();
}
}
There is my code, I want to add a time limit for how many seconds it takes until you can shoot again, right now you can just spam and make all of the bullets go in a straight line I need to wait before I let the player shoot again, Thanks! This will help out allot and i neede this in as few minutes as possible.
Use a flag to know when shooting is enabled and disabled. After each shot disable the ability to shoot. Then use a setTimeout to enable the shooting after a certain amount of time.
let shootingEnabled = true;
function tempDisableShooting(duration) {
shootingEnabled = false;
setTimeout(() => {
shootingEnabled = true;
}, duration);
}
function shooting() {
if (shootingEnabled && keyIsDown(KEY.SPACE)) {
if (powerup === 1) {
shoot(3);
} else {
shoot(1);
}
tempDisableShooting(1000); // Disable shooting for 1 second.
}
if (bullet) {
if (bullet.centerX[1] === screenWidth) {
bullets.remove(bullet);
}
}
}
Add property to track the disabled state of the shooting and a constant for the delay time in milliseconds.
let shootDisabled = false;
const shootDelayMS = 300;
Update your shoot function to only shoot if shootDisabled == false, update the shootDisabled to true after each shot, and to triggers a setTimeout which waits shootDelayMS milliseconds before setting shootDisabled to false again.
function shoot(amountofbulletstobeshot) {
if (shootDisabled == false) {
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let bullet = createSprite(bulletDirection[Math.abs(((Math.round(player.getDirection()/90))))]);
bullets.add(bullet);
bullet.centerX = player.centerX;
bullet.centerY = player.centerY;
bullet.setVelocity(11, player.getDirection());
shootDisabled = true;
setTimeout(() => shootDisabled = false, shootDelayMS );
}
}
one way is the hold the data in two variables: is_shooting, shot_reset.
if(is_shooting){
if(shot_reset>=x){ //x is frame count till able to shoot again)
shot_reset==0;
is_shooting=false;
}else{
shot_reset++
}
}

How to remove or add class in nav when the browser window goes down or up

I have nav with four elements. I try add class (eg. with underline in css) in this element witch user is on. But when user scroll up or down I want remove that class and add in diffrent element in nav depending on where the user stayed.
Here is my code:
let currentPosition = window.scrollY;
let basicFunctionPosition = document.querySelector("#basic-function").offsetTop;
let moreFunctionsPosition = document.querySelector("#more-functions").offsetTop;
let signUpPosition = document.querySelector("#sign-up").offsetTop;
let teamPosition = document.querySelector('#team').offsetTop;
let dataSectionInNav = "";
let dataSectionInNavTeam = "";
if (currentPosition > basicFunctionPosition && currentPosition < moreFunctionsPosition) {
dataSectionInNav = document.querySelector(".data-section-basic-func");
dataSectionInNav.classList.add("sectionPositionInNav");
} else if (currentPosition > moreFunctionsPosition && currentPosition < signUpPosition) {
dataSectionInNav = document.querySelector(".data-section-more-func");
dataSectionInNav.classList.add("sectionPositionInNav");
} else if (currentPosition > signUpPosition && currentPosition < teamPosition) {
dataSectionInNav = document.querySelector(".data-section-sign-up");
dataSectionInNav.classList.add("sectionPositionInNav");
dataSectionInNavTeam = document.querySelector(".data-section-team");
dataSectionInNavTeam.classList.add("sectionPositionInNav");
}
});
You need to loop over your conditionals when the user scrolls:
// Reference: http://www.html5rocks.com/en/tutorials/speed/animations/
let last_known_scroll_position = 0;
let ticking = false;
function doSomething(scroll_pos) {
// Do something with the scroll position
}
window.addEventListener('scroll', function(e) {
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(last_known_scroll_position);
ticking = false;
});
ticking = true;
}
});
The example above uses requestAnimationFrame to ease the rate at which your function runs.
Check the Docs for more information.
Afterwards I use this code,
document.addEventListener("scroll", function () {
let currentPosition = window.scrollY;
let basicFunctionPosition = document.querySelector("#basic-function").offsetTop;
let moreFunctionsPosition = document.querySelector("#more-functions").offsetTop;
let signUpPosition = document.querySelector("#sign-up").offsetTop;
let teamPosition = document.querySelector("#team").offsetTop;
let addClass = "";
let delateClass = "";
if (currentPosition < basicFunctionPosition) {
delateClass = document.querySelectorAll(".data-section-basic-func, .data-section-more-func, .data-section-sign-up, .data-section-team");
delateClass.forEach((item) => {
item.classList.remove("highlightNav");
});
} else if (currentPosition > basicFunctionPosition && currentPosition < moreFunctionsPosition) {
delateClass = document.querySelectorAll(".data-section-more-func, .data-section-sign-up, .data-section-team");
delateClass.forEach((item) => {
item.classList.remove("highlightNav");
});
addClass = document.querySelector(".data-section-basic-func");
addClass.classList.add("highlightNav");
} else if (currentPosition > moreFunctionsPosition && currentPosition < signUpPosition) {
delateClass = document.querySelectorAll(".data-section-basic-func, .data-section-sign-up, .data-section-team");
delateClass.forEach((item) => {
item.classList.remove("highlightNav");
});
addClass = document.querySelector(".data-section-more-func");
addClass.classList.add("highlightNav");
} else if (currentPosition > signUpPosition && currentPosition < teamPosition) {
delateClass = document.querySelectorAll(".data-section-basic-func, .data-section-more-func, .data-section-team");
delateClass.forEach((item) => {
item.classList.remove("highlightNav");
});
addClass = document.querySelector(".data-section-sign-up");
addClass.classList.add("highlightNav");
} else if (currentPosition > teamPosition) {
delateClass = document.querySelectorAll(".data-section-basic-func, .data-section-more-func, .data-section-sign-up");
delateClass.forEach((item) => {
item.classList.remove("highlightNav");
});
addClass = document.querySelector(".data-section-team");
addClass.classList.add("highlightNav");
}
});
Can you write the code more simply?

Parallax scroll not working on mobile

Hi there I have a parallax effect scroll on my website, it is all working good on desktop but mobile device it is not working properly when I attempt to even scroll/swipe down the page.
Here is the javascript:
var ticking = false;
var isFirefox = /Firefox/i.test(navigator.userAgent);
var isIe = /MSIE/i.test(navigator.userAgent) || /Trident.*rv\:11\./i.test(navigator.userAgent);
var scrollSensitivitySetting = 30;
var slideDurationSetting = 800;
var currentSlideNumber = 0;
var totalSlideNumber = $('.background').length;
function parallaxScroll(evt) {
if (isFirefox) {
delta = evt.detail * -120;
} else if (isIe) {
delta = -evt.deltaY;
} else {
delta = evt.wheelDelta;
}
if (ticking != true) {
if (delta <= -scrollSensitivitySetting) {
ticking = true;
if (currentSlideNumber !== totalSlideNumber - 1) {
currentSlideNumber++;
nextItem();
}
slideDurationTimeout(slideDurationSetting);
}
if (delta >= scrollSensitivitySetting) {
ticking = true;
if (currentSlideNumber !== 0) {
currentSlideNumber--;
}
previousItem();
slideDurationTimeout(slideDurationSetting);
}
}
}
function slideDurationTimeout(slideDuration) {
setTimeout(function () {
ticking = false;
}, slideDuration);
}
var mousewheelEvent = isFirefox ? 'DOMMouseScroll' : 'wheel';
window.addEventListener(mousewheelEvent, _.throttle(parallaxScroll, 60), false);
function nextItem() {
var $previousSlide = $('.background').eq(currentSlideNumber - 1);
$previousSlide.css('transform', 'translate3d(0,-130vh,0)').find('.content-wrapper1').css('transform', 'translateY(40vh)');
currentSlideTransition();
}
function previousItem() {
var $previousSlide = $('.background').eq(currentSlideNumber + 1);
$previousSlide.css('transform', 'translate3d(0,30vh,0)').find('.content-wrapper1').css('transform', 'translateY(30vh)');
currentSlideTransition();
}
function currentSlideTransition() {
var $currentSlide = $('.background').eq(currentSlideNumber);
$currentSlide.css('transform', 'translate3d(0,-15vh,0)').find('.content-wrapper1').css('transform', 'translateY(15vh)');
;
}
Your help would be appreciated thank you!

how to run JavaScript game animations sequentially after each one is finished

Currently, I am using an archaic method of setting a variable true at the start of the animation and false after the animation has played (see below.) I also think something might be wrong with how I process animations in the interval because when I add an animation to the array of animations to be processed, it isn't processed. Here's my code:
var animationDone = true;
function g_e(e){
return document.getElementById(e);
};
class Main{
constructor(){
this.animations = [];
this.tasks = [];
}
start_animating(){
var x = setInterval(function (){
if (animationDone == true){
try{
alert(this.animations[0]);
this.aminations[0].func(this.animations[0].args);
this.animations.shift();
}
catch(e){
}
}
},1);
}
add_animation(f, a){
this.animations.push({func:f, args:a});
alert("animation added");
}
start_working(){
var x = setInterval(function (){
try{
this.tasks[0].func(this.tasks[0].args);
this.tasks.shift();
}
catch(e){
}
},1);
}
animation_blink(){
var blink = 0;
window.setInterval(function blinking(){
if (blink == 0){
document.getElementById("blinker").innerHTML = ">";
blink= 1;
}
else if(blink == 1){
document.getElementById("blinker").innerHTML=" ";
blink = 0;
}
}, 1000);
}
animation_fade(object){
var fade = 0;
var fadeOut = 0;
animationDone = false;
var interval = setInterval(function startFade(){
g_e(object.element).style.opacity = fade;
if(fade>1 && fadeOut == 0){
fadeOut = 1;
}
else if(fade < 0){
clearInterval(interval);
}
else if(fadeOut == 0){
fade = fade + 0.2;
}
else if(fadeOut == 1){
fade = fade - 0.2;
}
}, 500);
animationDone = true;
}
plbl(object){
animationDone = false;
var p = plbl.intervals;
if (!p)
plbl.intervals = p = {};
if (p[object.destination])
clear();
function clear() {
clearInterval(p[object.destination]);
delete p[object.destination];
}
var i = 0;
var elem = document.getElementById(object.destination);
p[object.destination] = setInterval(function(){
checkChar = object.message.charAt(i);
if(checkChar =="|"){
elem.innerHTML += "<br>";
}
else{
elem.innerHTML += object.message.charAt(i);
}
i++;
if (i > message.length){
animationDone = true;
clear();
}
}, object.speed);
}
command(input){
alert(input);
if(input == "y"){
g_e("start").style.display = "none";
g_e("startUp").style.display = "block";
this.add_animation("test", "test");
}
}
get_input(){
var x = g_e("input").value;
g_e("input").value = "";
return x;
}
key_checker(event){
var key = event.keyCode;
if (key == 13){
this.command(this.get_input());
return false;
}
}
start(){
this.start_working();
this.start_animating();
this.animation_blink();
}
}
alert("compiled");
main = new Main();
main.start();

clearInterval is not clearing

Take a look at the function below, It purpose is to change the button text
to "Abort", "Abort 0", "Abort 1" and so on.
Once the counter reaches 10 another function should be executed, but if
the button is clicked, the counter should stop, and the button text should return
to it's original value ("Sync DB").
It seems I'm trying to clear out the interval in a wrong way.
Any assistance will be appreciated.
function sync_database(abort)
{
if (abort == true) { sync_db_btn.innerHTML = "Sync DB"; return false }
sync_db_btn.innerHTML = "Abort"
var i = 0;
sync_db_btn.addEventListener("click", function() { sync_database(true) } );
var x = setInterval(function() {
if (abort == true) {
clearInterval(x);
}
if (i < 10) {
sync_db_btn.innerHTML = "Abort " + i++;
}
}, 1000);
}
var x;
sync_db_btn.addEventListener("click", function() {
sync_database(true);
clearInterval(x);
} );
function sync_database(abort)
{
if (abort == true) { sync_db_btn.innerHTML = "Sync DB"; return false }
sync_db_btn.innerHTML = "Abort"
var i = 0;
x = setInterval(function() {
if (i < 10) {
sync_db_btn.innerHTML = "Abort " + i++;
}
}, 1000);
}
I think you need something like this:
var sync_db_btn = document.getElementById('but'),
abortSync = -1,
interval,
sync_database = function () {
var i = 0;
abortSync *= -1;
if (abortSync < 0) {
sync_db_btn.innerHTML = 'Sync DB';
clearInterval(interval);
return false;
}
sync_db_btn.innerHTML = 'Abort';
interval = setInterval(function () {
if (i < 10) {
sync_db_btn.innerHTML = 'Abort ' + i++;
} else {
sync_db_btn.innerHTML = 'Sync DB';
clearInterval(interval);
abortSync = -1;
}
}, 1000);
};
sync_db_btn.addEventListener('click', sync_database);
A live demo at jsFiddle.

Categories