Creating Delay in Javascript - javascript

I am relatively new to js and want to make a simple thing that changes an image when you click on it and then a couple of seconds later it reverts it to the first image again. It works to click on it, but then it never changes back. Here's my JavaScript:
function animation(){
var boom = document.getElementById("boom");
document.getElementById("boom").src = "file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Salamon.png";
}
if (boom.style.src == "file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Salamon.png") {
setTimeout(() => { document.getElementById("boom").src =
"file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Boom!.png";("World!"); }, 2000);
}
What's happening. I'm confused.

Just put them together in animation function. Now it's not completely clear what is the order of execution of those pieces of code.
const boom = document.getElementById("boom");
const origSrc = boom.src;
function animation(){
boom.src = "https://wholesalecelticvapours.com/media/catalog/product/s/a/sample-icon.png";
setTimeout(() => { boom.src = origSrc }, 2000);
}
boom.addEventListener('click', animation);
<img id="boom" src="https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg" width="150" height="150" />
<div>
click the image
</div>

You wrote in the condition:
boom.style.src == "..."
‍‍src‍‍‍ ‍The image is not in style
Example:
function animation(){
var boom = document.getElementById("boom");
document.getElementById("boom").src = "https://via.placeholder.com/420.png?text=Image+One";
}
if (boom.src == "https://via.placeholder.com/420.png?text=Image+One") {
setTimeout(() => { document.getElementById("boom").src =
"https://via.placeholder.com/420.png?text=Image+Two";("World!"); }, 2000);
}
<img id='boom' src="https://via.placeholder.com/420.png?text=Image+One">
My code:
var boom = document.getElementById("boom");
let imageOne = "https://via.placeholder.com/420.png?text=Image+One+Click+Me";
let imageTwo = "https://via.placeholder.com/420.png?text=Image+Two";
boom.addEventListener('click', function() {
if (boom.src == imageOne) {
setTimeout(() => {
boom.src = imageTwo;
setTimeout(() => {
boom.src = imageOne;
}, 2000);
}, 2000);
}
});
<img src="https://via.placeholder.com/420.png?text=Image+One+Click+Me" id='boom'>

Related

How to clear a sequence of audio with timeouts in React

I have set 4 timeout for audios in my application and I need to stop the audios after user click. The macro function is working correctly, however the clearTimout does not stop the sound. Anyone knows how to clear it?
export function handlePlay(audio) {
audio.currentTime = 0;
return audio.play();
}
export function handleConversation(clear) {
const timer1 = () => setTimeout(() => {
handlePlay(conversation[Math.floor(Math.random() * conversation.length)]);
}, TIME1);
const timer2 = () => setTimeout(() => {
handlePlay(conversation[Math.floor(Math.random() * conversation.length)]);
}, TIME2);
const timer3 = () => setTimeout(() => {
handlePlay(conversation[Math.floor(Math.random() * conversation.length)]);
}, TIME3);
const timer4 = () => setTimeout(() => {
handlePlay(conversation[Math.floor(Math.random() * conversation.length)]);
}, TIME4);
if (clear) {
console.log('enter clear');
return () => {
clearTimeout(timer1);
clearTimeout(timer2);
clearTimeout(timer3);
clearTimeout(timer4);
};
}
timer1();
timer2();
timer3();
timer4();
}
after clearTimeouts call this code
audio.pause();
audio.currentTime = 0;
Here a suggestion of what you could do.
I guess this could be improved further regarding how this handleConversation function is used, I didn't really get the whole idea and there is still some inconsistencies...
function createAudio(track) {
track.audio = conversation[Math.floor(Math.random() * conversation.length)];
}
export class Track {
constructor(time) {
this.time = time;
this.timeoutid = 0;
this.audio = new Audio();
}
timer() {
this.timeoutid = setTimeout(() => {
createAudio(this);
handlePlay(this.audio);
}, TIME1);
}
play() {
this.audio.currentTime = 0;
this.audio.play();
}
stop() {
this.audio.pause();
this.audio.currentTime = 0;
clearTimeout(this.timeoutid)
}
}
export function handleConversation(clear) {
const track1 = new Track(TIME1);
const track2 = new Track(TIME2);
const track3 = new Track(TIME3);
const track4 = new Track(TIME4);
// this part actually doesn't make a lot of sense, since all tracks will be recreated each time the function is called.
// I don't really understand how this is used.
// I imagine the tracks should more likey be stored outside the function in a persistent object.
// I will modify my answer if you provide more details about how you use handleConversation
if (clear) {
console.log('enter clear');
return () => {
[track1, track2, track3, track4].forEach(track => {
track.stop()
});
};
}
[track1, track2, track3, track4].forEach(track => {
track.timer()
});
}

Animation works not correctly

I have a block, when changing dynamic height. Open animation works correct, but when im closing block, animation drops, cant undestand why.
Link: dev.divisory.com/6/
code example:
let linetags_more = (e) => {
clearTimeout(timer);
let container = e.target.closest(".js-line-tags");
let spc = e.target.closest(".js-line-tags").querySelector(".line-tags__wrap").clientHeight;
const box = container.querySelector(".line-tags__box");
if(container.classList.contains("js-line-tags__more--active")) {
container.classList.remove("js-line-tags__more--active");
box.style.maxHeight = spc+"px";
timer = setTimeout(() => {
box.style.maxHeight = row+"px";
}, 100);
} else {
box.style.maxHeight = spc+"px";
timer = setTimeout(() => {
container.classList.add("js-line-tags__more--active");
box.removeAttribute("style");
}, 200);
}
e.preventDefault();
}
The problem is box.removeAttribute("style"). Just remove it and everything going to be OK.
if (container.classList.contains("js-line-tags__more--active")) {
container.classList.remove("js-line-tags__more--active");
box.style.maxHeight = spc + "px";
timer = setTimeout(() => {
box.style.maxHeight = "60" + "px";
}, 100);
} else {
box.style.maxHeight = spc + "px";
timer = setTimeout(() => {
container.classList.add("js-line-tags__more--active");
//box.removeAttribute("style");
}, 200);
}

How to flash background image on square after document.querySelectorAll('.square')

I am working on a whac a mole game where the background image should flash when the square is hit. For example an image that says "hit".
The square has been targeted correctly on function showImage(), tested with a console.log, and called in a forEach loop. I don't know the next step. I know I need to grab css class with background image of square and add an image. Maybe a set timer is involved. I have tried this and cannot get it working. See codepen
const squares = document.querySelectorAll('.square')
const mole = document.querySelector('.mole')
const timeLeft = document.querySelector('#time-left')
const score = document.querySelector('#score')
let result = 0
let hitPosition
let currentTime = 60
let timerId = null
function showImage() {
if ((document.onclick = squares)) {
squares.style.backgroundColor = 'green';
//console.log('it is working');
} else {
alert('it is not working');
}
}
function randomSquare() {
squares.forEach(square => {
square.classList.remove('mole')
})
let randomSquare = squares[Math.floor(Math.random() * 9)]
randomSquare.classList.add('mole')
hitPosition = randomSquare.id
}
squares.forEach(square => {
square.addEventListener('mousedown', () => {
if (square.id == hitPosition) {
result++
score.textContent = result
hitPosition = null
showImage();
}
})
})
function moveMole() {
timerId = setInterval(randomSquare, 500)
}
moveMole()
function countDown() {
currentTime--
timeLeft.textContent = currentTime
if (currentTime == 0) {
clearInterval(countDownTimerId)
clearInterval(timerId)
alert('GAME OVER! Your final score is ' + result)
}
}
let countDownTimerId = setInterval(countDown, 1000)
Sounds like this could handled by a class that displays an image in the background.
.bg-img {
background-image: url('');
}
And then in the function showImage() you set the class name bg-img on the element:
function showImage() {
squares.classList.add('bg-img');
setTimeout(function(){
squares.classList.remove('bg-img');
}, 1000);
}
And remove the class name again 1000 ms after.

setTimeOut to delay load of href from url in html - Not working

I have a link on all pages and every time the user clicks it I want to delay the next page load from the href with the <a> tag. I have tried to grab the link in the <a> tag in the HTML then tried to delay it but the timeout won't work. Can anyone kindly help?
var link = document.querySelector('a').getAttribute('href')
setTimeout(function() {
location.href = link
}, 4000);
This will help you I believe:
const a = document.querySelector('a');
a.addEventListener("click", (e) => {
e.preventDefault();
const link = e.target.href;
setTimeout(() => {
window.open(link)
}, 1000)
})
Working example on jsfiddle
if ( document.getElementById('primaryCTA') != null) {
var primaryCTA = document.getElementById("primaryCTA").onclick = showSpinner;
function showSpinner() {
var spin = document.getElementById("tick-animation-small");
if(spin.style.display == 'inline-flex')
spin.style.display = 'none';
else
spin.style.display = 'inline-flex';
var saving = document.getElementById("mini-spinner-copy");
if(saving.innerHTML == "Continue" )
saving.innerHTML = "Saving progress";
else
saving.innerHTML == "Continue";
var element = document.getElementById("mini-spinner-copy");
element.classList.add("fadeIn");
const a = document.querySelector('a');
a.addEventListener("click", (e) => {
e.preventDefault();
const link = e.target.href;
setTimeout(() => {
window.open(link)
}, 3000)
})
};
}

Javascript two interval image change

I have an image that I want to stay on screen for 5 seconds and then change to another image for .5 of a second and then change back to the original.
I've set the interval to change every 5 seconds but I can't seem to work out how to make it change for the according times.
Any help or direction would be greatly appeciated!
window.setInterval(function() {
var img = document.getElementById("glitch");
img.src = "2-01.svg";
}, 5000);
Try this:
const images = ["1.svg", "2.svg"]
var element = document.getElementById("glitch");
function showFirst() {
setTimeout(() => {
element.src = images[0];
showSecond()
}, 5000)
}
function showSecond() {
setTimeout(() => {
element.src = images[1];
showFirst()
}, 500)
}
showFirst()
You are always changing the image src to same "2-01.svg" every time. Please use some flag/condition to alternate the image src.
Here is what you can try ::
window.setInterval(function() {
var img = document.getElementById("glitch");
if(img.src == "2-01.svg") {
img.src = "2-00.svg"
}
else {
img.src = "2-01.svg";
}
}, 5000);
I was doing some test watching the thread.
If that can help you (this is not a clean code) :
img_to_change = document.querySelector("#glitch");
imgs = {"a":10, "b":2, "c":3}
keys = Object.keys(imgs)
run = function(i){
img_src = keys[i];
img_next_time = imgs[keys[i]];
img_to_change.src = img_src;
i = (i+1) == keys.length ? -1 : i;
setTimeout(() => {
img_to_change.src = img_src;
run(i+1);
}, img_next_time*1000)
}
run(0);
http://jsfiddle.net/pn3dyb5m/32/

Categories