Im_Ilya,
как-то так ... (два раза не жмакать, дождитесь окончания)
<!DOCTYPE html>
<html>
<head>
<style>
#red {
position: fixed;
width: 25px;
height: 25px;
background-color: red;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
body {
height: 100%;
}
</style>
</head>
<body>
<div id="red"></div>
<button id="start">Start</button>
<script>
let box = document.getElementById(`red`);
let delay = 10; //скорость
let coords = box.getBoundingClientRect();
let {
left: x,
top: y
} = coords;
let l = 0,
t = 0;
function edge() {
if (l == 0 && t > -2 * y && t <= 0) {
box.style.top = `${--t}px`;
setTimeout(edge, delay);
} else
if (l < 2 * x && t <= -2 * y) {
box.style.left = `${++l}px`;
setTimeout(edge, delay);
} else if (l >= 2 * x && t < 2 * y) {
box.style.top = `${++t}px`;
setTimeout(edge, delay);
} else if (l > 0 && t >= 2 * y) {
box.style.left = `${--l}px`;
setTimeout(edge, delay);
} else if (l <= 0 && t > 0) {
box.style.top = `${--t}px`;
t > 0 && setTimeout(edge, delay);
}
}
const start = document.getElementById('start')
start.addEventListener('click', edge)
</script>
</body>
</html>