Skip to content

Instantly share code, notes, and snippets.

@vladislavaSim
Created January 13, 2022 18:58
Show Gist options
  • Save vladislavaSim/d51a372aaeed09213d22d7d288a494dd to your computer and use it in GitHub Desktop.
Save vladislavaSim/d51a372aaeed09213d22d7d288a494dd to your computer and use it in GitHub Desktop.
moving square 2
let $square = document.querySelector('.square');
const topRight = [250, 0];
const topLeft = [0, 0];
const bottomRight = [250, 250];
const bottomLeft = [0, 250];
function delay(ms = 0) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function render(x, y) {
$square.style.top = y + 'px';
$square.style.left = x + 'px';
}
async function move(x, y, x1, y1) {
let xCondition;
let xStep;
let yCondition;
let yStep;
if(x < x1){
xCondition = _ => x < x1;
xStep = 1
}else{
xCondition = _ => x > x1;
xStep = -1;
}
if(y < y1){
yCondition = _ => y < y1;
yStep = 1
}else{
yCondition = _ => y > y1;
yStep = -1;
}
for(; xCondition() || yCondition(); ){
if(xCondition()){
x += xStep
}
if(yCondition()){
y += yStep
}
await delay();
render(x,y);
}
}
function eternalMoving() {
Promise.resolve().then(function resolver() {
if(moveByClockwise) {
return movingClockwise()
.then(resolver)
} else {
return movingOtherClockwise()
.then(resolver)
}
})
}
eternalMoving()
function movingClockwise() {
return move(...topLeft, ...topRight)
.then(() => move(...topRight, ...bottomRight))
.then(() => move(...bottomRight, ...bottomLeft))
.then(() => move(...bottomLeft, ...topLeft))
}
function movingOtherClockwise() {
return move(...topLeft, ...bottomLeft)
.then(() => move(...bottomLeft, ...bottomRight))
.then(() => move(...bottomRight, ...topRight))
.then(() => move(...topRight, ...topLeft))
}
let moveByClockwise = true;
$square.addEventListener('click', _ => {
moveByClockwise = !moveByClockwise
if(!moveByClockwise) {
$square.style.backgroundColor = 'red'
} else {
$square.style.backgroundColor = 'green'
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment