<div class="App">
<h1>Step 3</h1>
<div class="Example">
<div>3. setTimeout with delta fix (100ms)</div>
<div class="Example-position"></div>
<div class="Box"></div>
</div>
</div>
* {
box-sizing: border-box;
}
body {
background: #fdfdfd;
font-family: Helvetica, Arial, sans-serif;
}
.App {
position: relative;
max-width: 400px;
margin: 0 auto;
padding: 40px 20px;
}
h1 {
font-size: 1.2em;
font-weight: bold;
margin-bottom: 5px;
}
a {
color: #409ad7;
text-decoration: none;
border-bottom: 1px solid #ddd;
margin-bottom: 20px;
display: inline-block;
&:hover {
border-bottom-color: #409ad7;
}
}
.Example {
border: 1px solid #ddd;
border-radius: 3px;
background: #fff;
padding: 20px;
margin-bottom: 10px;
}
.Example-position {
margin-top: 5px;
color: #409ad7;
}
.Box {
width: 30px;
height: 30px;
background: #34ba9c;
margin-top: 20px;
border-radius: 2px;
}
View Compiled
const FRAME_DURATION = 1000 / 60; // 60fps frame duration
// If available we are using native "performance" API instead of "Date"
// It it's name suggests it is more performant, read more on MDN:
// https://developer.mozilla.org/en-US/docs/Web/API/Performance
const getTime = typeof performance === 'function' ? performance.now : Date.now;
const MAX_POSITION = 150;
const box = document.querySelector('.Box');
// Initial position
let position = 0;
// Initial time
let lastUpdate = getTime();
function animate() {
const now = getTime();
// This is the main part
// We are checking how much time has passed since the last update
// and translating that to frames
const delta = (now - lastUpdate) / FRAME_DURATION;
// Updating scene logic
// We want to move the box 1px per each 16.66ms (60fps)
// so we are multipling 1px with the number of frames passed
position += 1 * delta;
// Reset position
if (position > MAX_POSITION) {
position -= MAX_POSITION;
}
// Render updated scene
box.style.transform = `translateX(${ position }px)`;
// Update last updated time
lastUpdate = now;
// Fake 10fps using "setTimeout"
setTimeout(animate, 100);
}
animate();
View Compiled
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.