I made a code for an animation on the button
cta.addEventListener("mouseover", () => {
setTimeout(() => {
audio.play()
audio.volume = .06;
imgs[0].style.transform = "translate(0, 0)";
setTimeout(() => {
imgs[2].style.transform = "translate(0, 0)";
}, 150);
setTimeout(() => {
imgs[1].style.transform = "translate(0, 0)";
}, 200);
setTimeout(() => {
imgs[5].style.transform = "translate(0, 0)";
}, 250);
setTimeout(() => {
imgs[3].style.transform = "translate(0, 0)";
}, 300);
setTimeout(() => {
imgs[4].style.transform = "translate(0, 0)";
}, 600);
}, 100);
});
But this is not very pleasant.
How to improve this code?? Make a setInterval only and make this value increase with each execution??
Slightly better version of code:
cta.addEventListener("mouseover", () => {
setTimeout(() => {
audio.play()
audio.volume = .06;
imgs[0].style.transform = "translate(0, 0)";
transformImage(imgs[2], 150);
transformImage(imgs[1], 200);
transformImage(imgs[5], 250);
transformImage(imgs[3], 300);
transformImage(imgs[4], 600);
}, 100);
});
function transformImage(img, interval) {
setTimeout(() => {
img.style.transform = "translate(0, 0)";
}, interval);
}
Further improvement:
cta.addEventListener("mouseover", () => {
setTimeout(() => {
audio.play()
audio.volume = .06;
imgs[0].style.transform = "translate(0, 0)";
let offset = 150;
imgs.forEach(img => transformImage(img, offset+=50));
}, 100);
});
function transformImage(img, interval){
setTimeout(() => {
img.style.transform = "translate(0, 0)";
}, interval);
}
The only way of improvement I can see is to use a for loop:
cta.addEventListener("mouseover", () => { setTimeout(() => { audio.play() audio.volume =.06; let times = [0, 200, 150, 300, 600, 250] times.forEach(function(let idx in times) { setTimeout(() => { imgs[idx].style.transform = "translate(0, 0)"; }, times[idx]); } }, 100);) });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.