I’m trying to make clones forever but wait a bit before every clone but I can’t find a way to do this.
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
while (true){
// Clone the image with id "bullet"
sleep(2000).then(() => {const originalBullet = document.getElementById("bullet");
const clonedBullet = originalBullet.cloneNode(true);
document.body.appendChild(clonedBullet);
// Set random y position and specific x position
clonedBullet.style.top = Math.floor(Math.random() * (450 - 250 + 1)) + 250;
clonedBullet.style.left = "0px";
// Move the cloned image to the right until it reaches the edge
const moveInterval = setInterval(() => {
const rect = clonedBullet.getBoundingClientRect();
if (rect.right >= window.innerWidth) {
clearInterval(moveInterval); // Stop moving
document.body.removeChild(clonedBullet); // Delete the clone
} else {
clonedBullet.style.left = (rect.left + 1) + "px"; // Move right
}
}, 5); });.
}
This is what I did, but it infact did not work.
2
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function cloneBullets() {
while (true) {
// Wait for 2000 milliseconds (2 seconds)
await sleep(2000);
// Clone the image with id "bullet"
const originalBullet = document.getElementById("bullet");
if (originalBullet) {
const clonedBullet = originalBullet.cloneNode(true);
document.body.appendChild(clonedBullet);
// Set random y position and specific x position
clonedBullet.style.position = 'absolute';
clonedBullet.style.top = Math.floor(Math.random() * (450 - 250 + 1)) + 250 + 'px';
clonedBullet.style.left = "0px";
// Move the cloned image to the right until it reaches the edge
const moveInterval = setInterval(() => {
const rect = clonedBullet.getBoundingClientRect();
if (rect.right >= window.innerWidth) {
clearInterval(moveInterval); // Stop moving
document.body.removeChild(clonedBullet); // Delete the clone
} else {
clonedBullet.style.left = (rect.left + 1) + "px"; // Move right
}
}, 5);
}
}
}
// Start the cloning process
cloneBullets();
This should do it by making the function asynchronous and using await, the loop will then pause for the specified duration before each iteration, resulting in the desired behaviour. You could also look at CSS animations to do this, might be overall easier.