Kevin Powell - CommunityKP-C
Kevin Powell - Community3y ago
48 replies
Matt

Infinite Loop Question

Hello!
I'm attempting to infinitely move an object randomly across the viewport. Below contains some code I used to be able to set random position (based on current position). However, I need to be able to loop this consistently. Which loop should I use?

var element = document.querySelector(".blob");
var blob = element.getBoundingClientRect();

const x = blob.x;
const y = blob.y;

function randomX(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randomY(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

element.style.left = element.style.left + randomX(x, 1000) + "px";
element.style.top= element.style.top + randomX(y, 1000) + "px";
Was this page helpful?