Open devSoyoung opened 4 years ago
// main.js
let requestId = 0;
let lpos = 0;
let targetEl = document.querySelector('#animated');
function render() {
targetEl.style.left = `${(lpos += 3) % 600}px`;
requestId = window.requestAnimationFrame(render);
// requestId = setTimeout(render, 1000 / 60);
}
function start() {
requestId = window.requestAnimationFrame(render);
// requestId = setTimeout(render, 1000 / 60);
}
function stop() {
if (requestId) {
window.cancelAnimationFrame(requestId);
// clearInterval(requestId);
}
}
requestAnimationFrame
: 윈도우 크기를 변경하는 동안 애니메이션이 실행되지 않아서 크기 변경이 끝났을 때 기존 위치에서 애니메이션이 시작됨setTimeout
: 윈도우 크기를 변경하는 동안 애니메이션이 실행되어 크기 변경이 끝났을 때 요소가 순간이동함requestAnimationFrame
이 창 크기를 변경할 때 보다 깔끔한 애니메이션을 구현해줌
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div {
position: absolute;
left: 10px;
top: 100px;
padding: 50px;
background: yellowgreen;
color: white;
}
</style>
</head>
<body>
<div id="animated"></div>
<button onClick="start()">Start</button>
<button onClick="stop()">Stop</button>
<script src="main.js"></script>
</body>
</html>
window.requestAnimationFrame
window.cancleAnimationFrame
requestAnimationFrame
에서 반환한 requestId를 전달하면 해당 request가 더 이상 수행되지 않음Reference