There are some components stacked on top of each other and the last component has a timer. I want the timer to start only when that component is visible on screen or when scroll is reached to that component. [REPL]
let count_val = 80;
let count = 0;
function startTimer() {
let count_interval = setInterval(() => {
count += 1;
if(count >= count_val) {
clearInterval(count_interval);
}
}, 100);
}
// check if scroll reached to component and run below function.
startTimer();
How do I achieve this?
Like commented this can be achieved using Intersection Observer and an action
REPL
<script>
let count_val = 80;
let count = 0;
function timer(node) {
let interval
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if(entry.isIntersecting) {
interval = setInterval(() => {
count += 1;
if(count === count_val) {
clearInterval(interval);
}
}, 100);
} else {
clearInterval(interval)
count = 0
}
})
})
observer.observe(node)
return {
destroy: () => observer.disconnect()
}
}
</script>
<div use:timer>
<p>
Counter - {count}
</p>
</div>
<style>
div {
height: 100vh;
display: grid;
place-items: center;
background-color: teal;
color: #0a0a0a;
font-size: 4rem;
}
</style>
Related
My goal I want to run loop that decrements a global variable stepwise in n ms (for Example: 200ms) time intervals.
Thanks in advance!
What i already tried
I tried to use ascy await. But in combination with css transition i run in an infinite loop (In codepen.io). But here in SO you will see that it starts not running smoothly if you keep pressing arrow up.
const procentage = document.querySelector(".procentage");
const green = engine.querySelector(".green");
let number = 0;
let decrementing = false;
window.addEventListener('keydown', (e) => {
e = e || window.event;
e.preventDefault();
if (e.keyCode == '38') {
console.log("accelerate");
actionHandler( number++ );
decrementing = false;
downLoop();
}
});
function actionHandler(num) {
procentage.innerHTML = num;
const str = num + "%"
green.style.width = str;
procentage.innerHTML = str;
}
window.addEventListener('keyup', (e) => {
e = e || window.event;
e.preventDefault();
if (e.keyCode == '38') {
console.log("decelerate");
decrementing = true;
downLoop();
}
});
async function downLoop() {
if (! decrementing) {
return false
};
const timer = ms => new Promise(res => setTimeout(res, ms));
while (number > 1) {
// how to decrement ever 200ms???
actionHandler( number-- );
await timer(200)
}
}
#engine {
background-color:black;
height: 50px;
position: relative;
}
p {
text-align: center;
}
.green {
background:green;
height: 50px;
width:0%;
transition: width 0.2s;
text-align:center;
}
.procentage {
position:absolute;
top: 50%;
left: 50%;
transform: translate(0%,-50%);
color: white;
fon-weight: bold;
font-size:28px;
}
<div id="engine">
<div><span class="procentage">0</span></div>
<div class="green"></div>
</div>
<p>press arrow Up</p>
Whenever you animate, you shouldn't rely on setInterval or setTimeout, because that means that you will update "somewhere after X milliseconds" which will often end up in the middle of a screen repaint, and will therefor cause janky animation.
Instead, you should use RequestAnimationFrame which does a calculation before every repaint. So if you got a monitor with a framerate of 60 Hz, that means that you will do 60 repaints every second. For each repaint, check if enough time have passed since the last update (shouldTriggerUpdate() below) and then check if you should update the number.
I also added the class KeyHandler to keep track of which keys that have been pressed.
I got sloppy at the end and just added a decrement as an "else" of the if statement. You will figure something out when you get there when you want to set up more keys to be pressed.
You shouldn't use KeyboardEvent.keyCode, but instead KeyboardEvent.code.
const procentage = document.querySelector(".procentage");
const green = engine.querySelector(".green");
let number = 0;
let speed = 200 // ms
let lastUpdated = 0; // ms
let animationId = 0; // use later on to pause the animation
class KeyHandler {
ArrowLeft = false
ArrowUp = false
ArrowRight = false
ArrowDown = false
#setKey(code, value) { // private method
if (typeof this[code] != undefined) {
this[code] = value;
}
}
set pressedKey(code) {
this.#setKey(code, true);
}
set releasedKey(code) {
this.#setKey(code, false);
}
}
let keyHandler = new KeyHandler();
window.addEventListener('keydown', (e) => {
e = e || window.event;
e.preventDefault();
keyHandler.pressedKey = e.code;
});
window.addEventListener('keyup', (e) => {
e.preventDefault();
keyHandler.releasedKey = e.code
});
function actionHandler(num) {
const str = num + "%"
green.style.width = str;
procentage.innerHTML = str;
}
function shouldTriggerUpdate(timeInMillis) {
let difference = timeInMillis - lastUpdated;
return difference >= speed;
}
function planeAnimation() {
let timeInMillis = new Date().getTime();
if (shouldTriggerUpdate(timeInMillis)) {
lastUpdated = timeInMillis;
if (keyHandler.ArrowUp) {
actionHandler(++number)
} else if (number > 0) {
actionHandler(--number)
}
}
animationId = requestAnimationFrame(planeAnimation)
}
animationId = requestAnimationFrame(planeAnimation);
#engine {
background-color: black;
height: 50px;
position: relative;
}
p {
text-align: center;
}
.green {
background: green;
height: 50px;
width: 0%;
transition: width 0.2s;
text-align: center;
}
.procentage {
position: absolute;
top: 50%;
left: 50%;
transform: translate(0%, -50%);
color: white;
fon-weight: bold;
font-size: 28px;
}
<div id="engine">
<div><span class="procentage">0</span></div>
<div class="green"></div>
</div>
<p>press arrow up</p>
From the above comments ...
"Instead of incrementing each time the number value push a new async timer function, set to 200 msec delay but not immediately triggered, into an array. Create an async generator from it and iterate over the latter via the for-await...of statement where one could decrement number again." – Peter Seliger
"#PeterSeliger Hi Peter! Thank you for your comment. Can you make a small example please?" – Maik Lowrey
And here the requested demonstration.
function createWait(delay) {
return async function wait () {
let settle;
const promise = new Promise((resolve) => { settle = resolve;});
setTimeout(settle, delay, { delay, state: 'ok' });
return promise;
};
}
async function* getWaitIterables(list) {
let wait;
while (wait = list.shift()) {
yield wait();
}
}
// demo for ...
// - creating an async `wait` function
// or a list of such kind.
// - creating an async generator from
// a list of async `wait` functions.
// - iterating an async generator of
// async `wait` functions.
const waitingList = [ // const waitingList = [];
2000, // waitingList.push(createWait(2000));
1000, // waitingList.push(createWait(1000));
3000, // waitingList.push(createWait(3000));
].map(createWait); // - The OP of cause needs to push into.
let number = 3; // - The incremented `number` value e.g. ... 3.
(async () => {
for await (const { delay, state } of getWaitIterables(waitingList)) {
--number;
console.log({ number, delay, state });
}
})();
console.log('... running ...', { number });
.as-console-wrapper { min-height: 100%!important; top: 0; }
could someone help me out with this piece of Javascript?
I am trying to make some sort of "whack-a-mole" game, and this is what I came up with; I set up a way to keep track of the score by adding 1 (score++) every time the user clicks on the picture that pops up. My problem is that the code runs the function more times than needed—for example, if I click on the first image that pops up, the function to add +1 to the score fires once, if I click on the second, the function fires twice, threee times on the third, etc...
What am I doing wrong?
//gid
const grid = document.querySelector('.grid');
//score display value
const scoreValue = document.querySelector('#scoreValue');
//score
let score = 0;
const timer = setInterval(() => {
//output random number
let output = Math.floor(Math.random() * 16);
//select hole
let hole = document.getElementById(output);
hole.innerHTML = '<img src="img/kiseki.png" alt=""></img>';
setTimeout(() => {
hole.innerHTML = '';
}, 2000);
grid.addEventListener('click', e => {
if (e.target.tagName === "IMG") {
score++;
scoreValue.textContent = score;
console.log(score);
hole.innerHTML = '';
}
});
}, 4000);
Since you're ading a new eventListener every time the interval runs, so in order to solve your problem, just add it once, before starting the setInterval that pops your moles.
Example code:
const grid = document.querySelector('.grid');
const scoreValue = document.querySelector('#scoreValue');
const newMoleTimer = 4000;
const moleTimeout = 2000
let score = 0;
let hole;
grid.addEventListener('click', e => {
if (e.target.tagName === "IMG") {
score++;
scoreValue.textContent = score;
if(hole) hole.innerHTML = '';
}
});
const timer = setInterval(() => {
let output = Math.floor(Math.random() * 16);
hole = document.getElementById(output);
hole.innerHTML = '<img src="img/kiseki.png" alt=""></img>';
setTimeout(() => {
hole.innerHTML = '';
}, moleTimeout);
}, newMoleTimer);
*updated code according to #Meika commentary
You need to separate the eventlistener from the settimer function.
In this example I created div elements with a color. Only blue color score and can only score one point pr. timer.
//gid
const grid = document.querySelector('#grid');
//score display value
const scoreValue = document.querySelector('#scoreValue');
//score
let score = 0;
grid.addEventListener('click', e => {
if (e.target.score) {
score++;
scoreValue.textContent = score;
e.target.score = false;
}
});
const timer = setInterval(() => {
//output random number
let output = 1 + Math.floor(Math.random() * 3);
//select hole
let hole = document.querySelector(`div.box:nth-child(${output})`)
hole.classList.add('blue');
hole.score = true;
setTimeout(() => {
hole.classList.remove('blue');
hole.score = false;
}, 1000);
}, 2000);
div#grid {
display: flex;
}
div.box {
width: 100px;
height: 100px;
border: thin solid black;
background-color: red;
}
div.blue {
background-color: blue;
}
<div id="grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div id="scoreValue"></div>
Rewrite, a mole is a DOM element, attach the click event to it on load then, in the game timer you only need to pick a random mole and toggle a class, within the click event you can check for that class, if it is there then the mole must be showing, add a score.
For example:
const moles = document.querySelectorAll('.grid .mole')
const hitScore = document.querySelector('.score .hit')
const missScore = document.querySelector('.score .miss')
const gameOver = document.querySelector('.gameover')
let score = {
hit: 0,
miss: 0
}
// assign clicks to all moles
moles.forEach((elm) => {
elm.addEventListener('click', e => {
if (e.target.classList.contains('show')) {
hitScore.textContent = ++score.hit
e.target.classList.remove('show')
}
})
})
// game timer
const timer = setInterval(() => {
// get random mole element
const randMole = moles[Math.floor(Math.random() * moles.length)]
// check if has class, i.e miss
if (randMole.classList.contains('show')) {
missScore.textContent = ++score.miss
}
// toggle show
randMole.classList.toggle('show')
// 5 misses and game over
if (score.miss >= 5) {
clearInterval(timer)
gameOver.style.display = 'block'
}
}, 1000)
.grid {
width: 310px;
height: 310px;
background-image: url(https://i.imgur.com/s6lUgud.png);
position: relative
}
.mole {
position: absolute;
width: 100px;
height: 100px
}
.mole.show {
background-image: url(https://i.imgur.com/uScpWV4.png);
background-repeat: no-repeat;
background-size: 48px 51px;
background-position: center
}
.mole:nth-of-type(1) {
top: 0;
left: 0
}
.mole:nth-of-type(2) {
top: 0;
left: 108px
}
.mole:nth-of-type(3) {
top: 0;
left: 214px
}
.mole:nth-of-type(4) {
top: 100px;
left: 0
}
.mole:nth-of-type(5) {
top: 100px;
left: 108px
}
.mole:nth-of-type(6) {
top: 100px;
left: 214px
}
.mole:nth-of-type(7) {
top: 200px;
left: 0px
}
.mole:nth-of-type(8) {
top: 200px;
left: 107px
}
.mole:nth-of-type(9) {
top: 200px;
left: 214px
}
.gameover {
display: none;
color: red
}
<div class="score">
<strong>Score:</strong> Hit:
<span class="hit">0</span> Miss:
<span class="miss">0</span>
</div>
<div class="gameover">Game Over</div>
<div class="grid">
<div class="mole"></div>
<div class="mole"></div>
<div class="mole"></div>
<div class="mole"></div>
<div class="mole"></div>
<div class="mole"></div>
<div class="mole"></div>
<div class="mole"></div>
<div class="mole"></div>
</div>
I am working on a pure JavaScript infinite scroll with the help of the Intersection Observer API.
The scrollable items are posts from the jsonplaceholder.typicode.com API.
I load 5 posts initially, then 5 more with every scroll to the bottom.
class InfiniteScroll {
constructor() {
this.postsContainer = document.querySelector('#postsContainer');
this.visiblePosts = [];
this.postsLot = [];
this.observer = null;
this.hasNextPage = true;
this.postsUrl = 'https://jsonplaceholder.typicode.com/posts';
this.limit = 5;
this.iterationCount = 0;
}
loadPosts() {
fetch(this.postsUrl)
.then(res => res.json())
.then(posts => {
this.postsLot = posts.slice(this.iterationCount * this.limit, this.limit);
// Add items to the array of visible posts
// with every iteration
if(this.postsLot.length > 0) {
this.postsLot.map(entry => {
return this.visiblePosts.push(entry);
});
}
this.renderVisiblePosts();
})
.catch(err => console.log(err));
}
renderVisiblePosts() {
let output = '';
this.visiblePosts.forEach(post => {
output += `<div class="post">
<h2>${post.id} ${post.title}</h2>
<p>${post.body}</p>
</div>`;
});
this.postsContainer.innerHTML = output;
}
getLastPost() {
return this.visiblePosts[this.visiblePosts.length - 1];
}
iterationCounter() {
if (this.hasNextPage) {
this.iterationCount = this.iterationCount + 1;
}
}
bindLoadMoreObserver() {
if (this.postsContainer) {
this.observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry && entry.isIntersecting) {
console.log('bottom');
observer.unobserve(entry.target);
this.loadPosts();
this.iterationCounter();
if (this.hasNextPage) {
observer.observe(this.getLastPost());
}
}
});
});
this.observer.observe(this.getLastPost());
}
}
init() {
this.getLastPost();
this.loadPosts();
this.bindLoadMoreObserver();
}
}
const infiniteScroll = new InfiniteScroll();
infiniteScroll.init();
body, body * {
margin: 0;
padding: 0;
}
body {
font-family: Arial, Helvetica, sans-serif;
}
.post {
margin: 20px;
padding: 15px;
border: 1px solid #ccc;
border-radius: 5px;
}
p {
line-height: 1.5;
}
<div id="postsContainer"></div>
The problem
Instead of observing when the last element comes into view, the browser throws the error:
Uncaught TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.
You're not observing the Element as per your current implementation. You're observing the last object in your visiblePosts array which is not an element.
You can get the last element by using this.postsContainer.lastElementChild provided that till then this.postsContainer has children Elements.
The pictures change themselves every 3 seconds.
I would like to add simple animation to the photo during the change.
Preferably in vaniilla js.
let index = 1;
const changeImg = () => {
index++;
img.setAttribute('src', `img/img${index}.png`);
if (index === 3) {
index = 0;
}
};
setInterval(changeImg, 3000);
If you use something like animate.css, or create your own animation class you could do it like this:
(Im assuming you're getting the image by a query selector/getElementById)
let index = 1;
const changeImg = () => {
index++;
img.classList.add('animate__animated');
img.classList.add('animate__bounce');
setTimeout(() => {
img.setAttribute('src', `img/img${index}.png`);
img.classList.remove('animate__animated');
img.classList.remove('animate__bounce');
}, 300); // This delay is assuming the animation duration is 300ms, you need to change this to the length of the animation
if (index === 3) {
index = 0;
}
};
setInterval(changeImg, 3000);
As you suggested an example in vanilla JavaScript (no libraries), here you go.
(function slideShow() {
let imgs = [
"https://picsum.photos/id/237/200/300",
"https://picsum.photos/id/238/200/300",
"https://picsum.photos/id/239/200/300"
];
let index = 0;
const frontImg = document.getElementById("slideshow__img--front");
const backImg = document.getElementById("slideshow__img--back");
frontImg.src = imgs[index];
const changeSlideShowImg = () => {
const currImgSrc = imgs[index];
index++;
if (index >= imgs.length) index = 0;
const newImgSrc = imgs[index];
backImg.src = newImgSrc;
frontImg.classList.add("slideshow__img--fadeout");
setTimeout(() => {
frontImg.src = newImgSrc;
frontImg.classList.remove("slideshow__img--fadeout");
}, 500);
};
setInterval(changeSlideShowImg, 3000);
})()
.slideshow {
width: 200px;
height: 300px;
position: relative;
}
.slideshow__img {
position: absolute;
left: 0;
top: 0;
opacity: 1;
}
#slideshow__img--front {
z-index: 2;
}
.slideshow__img.slideshow__img--fadeout {
transition: opacity 0.5s ease-in;
opacity: 0;
}
<div class="slideshow">
<img id="slideshow__img--front" class="slideshow__img" />
<img id="slideshow__img--back" class="slideshow__img" />
</div>
How i can create animated timer using React-hooks
Here is complete code what i had tried
Basically i was trying Displays the progress of time remaining as an animated ring.
But somehow i am getting failed in it
I just followed this blog for creating animated timer https://css-tricks.com/how-to-create-an-animated-countdown-timer-with-html-css-and-javascript/
function setRemainingPathColor(timeLeft) {
const { alert, warning, info } = COLOR_CODES;
console.log(dataFromDiv);
if (timeLeft <= alert.threshold) {
dataFromDiv.current
.querySelectorAll("base-timer-path-remaining")
.classList.remove(warning.color);
dataFromDiv.current
.querySelectorAll("base-timer-path-remaining")
.classList.add(alert.color);
} else if (timeLeft <= warning.threshold) {
dataFromDiv.current
.querySelectorAll("base-timer-path-remaining")
.classList.remove(info.color);
dataFromDiv.current
.querySelectorAll("base-timer-path-remaining")
.classList.add(warning.color);
}
}
React.useEffect(() => {
let timer;
let timePassed = 0;
let timeLeft;
timer = counter > 0 && setTimeout(() => setCounter(counter - 1), 1000);
timePassed = timePassed += 1;
timeLeft = counter - timePassed;
setRemainingPathColor(timeLeft);
return () => {
if (timer) {
clearTimeout(timer);
}
};
}, [counter]);
The error you were getting is because dataFromDiv.current.querySelectorAll(...) was always returning undefined because dataFromDiv.current was a reference to div#base-timer-path-remaining which is the element you wanted to modify. So, your code would work fine by just removing .querySelectorAll(...).
However, there are some better ways to structure your code:
Instead of doing direct dom manipulations, it's easier in this case to just figure out which color you want using useMemo to set up derived data based on the counter value.
You can also use an interval instead of a timer as it's easier to work with and a little bit cleaner. This also uses the updater function form of setCounter so that the effect doesn't need to have counter in the dependencies.
I also added a reset button to my example below so you don't have to re-run it every time.
const pathColor = React.useMemo(() => {
const { alert, warning, info } = COLOR_CODES;
if (counter <= alert.threshold) {
return alert.color;
} else if (counter <= warning.threshold) {
return warning.color;
} else {
return info.color;
}
}, [counter]);
React.useEffect(() => {
const timerId = setInterval(() => {
setCounter(counter => {
if (counter <= 0) {
clearInterval(timerId);
return counter;
}
return counter - 1;
});
}, 1000);
return () => {
clearInterval(timerId);
};
}, [timerReset]); // this timerReset is to make sure that the interval starts off again whenever the reset button is pressed.
This line is simply a way to force a re-render. The reducer function x=>x+1 increments the timerReset value whenever dispatch (renamed to resetTimer) is called. And then I use timerReset to force the effect to re-run in order to start the interval again (if it stopped)
const [timerReset, resetTimer] = React.useReducer(x => x + 1, 0);
const padTime = time => {
return String(time).length === 1 ? `0${time}` : `${time}`;
};
const format = time => {
const minutes = Math.floor(time / 60);
const seconds = time % 60;
return `${minutes}:${padTime(seconds)}`;
};
const WARNING_THRESHOLD = 10;
const ALERT_THRESHOLD = 5;
const COLOR_CODES = {
info: {
color: "green"
},
warning: {
color: "orange",
threshold: WARNING_THRESHOLD
},
alert: {
color: "red",
threshold: ALERT_THRESHOLD
}
};
function App() {
const [counter, setCounter] = React.useState(20);
const [timerReset, resetTimer] = React.useReducer(x => x + 1, 0);
const pathColor = React.useMemo(() => {
const { alert, warning, info } = COLOR_CODES;
if (counter <= alert.threshold) {
return alert.color;
} else if (counter <= warning.threshold) {
return warning.color;
} else {
return info.color;
}
}, [counter]);
React.useEffect(() => {
const timerId = setInterval(() => {
setCounter(counter => {
if (counter <= 0) {
clearInterval(timerId);
return counter;
}
return counter - 1;
});
}, 1000);
return () => {
clearInterval(timerId);
};
}, [timerReset]);
return (
<div className="App">
<div className="base-timer">
<svg
className="base-timer__svg"
viewBox="0 0 100 100"
xmlns="http://www.w3.org/2000/svg"
>
<g className="base-timer__circle">
<circle
className="base-timer__path-elapsed"
cx="50"
cy="50"
r="45"
/>
<path
id="base-timer-path-remaining"
className={`base-timer__path-remaining ${pathColor}`}
d="
M 50, 50
m -45, 0
a 45,45 0 1,0 90,0
a 45,45 0 1,0 -90,0
"
/>
</g>
</svg>
<span id="base-timer-label" className="base-timer__label">
{format(counter)}
</span>
</div>
<button
onClick={() => {
setCounter(20);
resetTimer();
}}
>
reset timer
</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
/* Sets the containers height and width */
.base-timer {
position: relative;
height: 300px;
width: 300px;
}
/* Removes SVG styling that would hide the time label */
.base-timer__circle {
fill: none;
stroke: none;
}
/* The SVG path that displays the timer's progress */
.base-timer__path-elapsed {
stroke-width: 7px;
stroke: grey;
}
.base-timer__path-remaining {
stroke-width: 7px;
stroke-linecap: round;
transform: rotate(90deg);
transform-origin: center;
transition: 1s linear all;
fill-rule: nonzero;
stroke: currentColor;
}
.base-timer__path-remaining.green {
color: rgb(65, 184, 131);
}
.base-timer__path-remaining.orange {
color: orange;
}
.base-timer__path-remaining.red {
color: red;
}
.base-timer__label {
position: absolute;
width: 300px;
height: 300px;
top: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 48px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>