-
Notifications
You must be signed in to change notification settings - Fork 0
/
requestAnimationFrame.html
70 lines (64 loc) · 2.09 KB
/
requestAnimationFrame.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<!DOCTYPE html>
<html>
<head>
<title>JS Playground</title>
<style>
.row {
height: 25px;
position: relative;
}
.square {
position: absolute;
height: 25px;
width: 25px;
}
#square1 {
background-color: tomato;
left: 500px;
}
#square2 {
background-color: mediumturquoise;
}
</style>
</head>
<body>
<div class="row">
<div class="square" id="square1"></div>
</div>
<div class="row">
<div class="square" id="square2"></div>
</div>
<script>
// This example moves two squares using two different timing functions.
// #square1 is moved 10px every time setTimeout() is called.
// #square2 is moved 10px every time requestAnimationFrame() is called.
// #square1 ends up moving faster because setTimeout() is called many times between renders,
// but requestAnimationFrame() gets called only once per render.
// In this example, setTimeout() ends up wasting resources calculating positions that are never rendered.
function moveSquare(selector) {
const parentWidth = document.querySelector(selector).parentElement.clientWidth;
let currentLeft = document.querySelector(selector).style['left']; // TODO: this is not getting the 500px on the first iteration
if (currentLeft) {
currentLeft = Number(currentLeft.substr(0, currentLeft.length - 2));
}
else {
currentLeft = 0;
}
if (currentLeft > parentWidth) {
currentLeft = 0;
}
document.querySelector(selector).style['left'] = `${currentLeft+10}px`;
}
function moveSquare1() {
moveSquare('#square1');
setTimeout(moveSquare1, 0);
}
function moveSquare2() {
moveSquare('#square2');
requestAnimationFrame(moveSquare2);
}
moveSquare1();
moveSquare2();
</script>
</body>
</html>