Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 22 additions & 14 deletions Week1/prep-exercises/1-catwalk-promises/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,44 @@ const STEP_INTERVAL_MS = 50;
const DANCE_TIME_MS = 5000;
const DANCING_CAT_URL =
'https://media1.tenor.com/images/2de63e950fb254920054f9bd081e8157/tenor.gif';
const WALKING_CAT_URL = 'http://www.anniemation.com/clip_art/images/cat-walk.gif';

function walk(img, startPos, stopPos) {
return new Promise((resolve) => {
// Resolve this promise when the cat (`img`) has walked from `startPos` to
// `stopPos`.
// Make good use of the `STEP_INTERVAL_PX` and `STEP_INTERVAL_MS`
// constants.
let pos = startPos;
const timer = setInterval(() => {
pos += STEP_SIZE_PX;
img.style.left = `${pos}px`;
if (pos >= stopPos) {
clearInterval(timer);
resolve();
}
}, STEP_INTERVAL_MS);
});
}

function dance(img) {
return new Promise((resolve) => {
// Switch the `.src` of the `img` from the walking cat to the dancing cat
// and, after a timeout, reset the `img` back to the walking cat. Then
// resolve the promise.
// Make good use of the `DANCING_CAT_URL` and `DANCE_TIME_MS` constants.
const originalSrc = img.src;
img.src = DANCING_CAT_URL;
setTimeout(() => {
img.src = originalSrc;
resolve();
}, DANCE_TIME_MS);
});
}

function catWalk() {
async function catWalk() {
const img = document.querySelector('img');
const startPos = -img.width;
const centerPos = (window.innerWidth - img.width) / 2;
const stopPos = window.innerWidth;

// Use the `walk()` and `dance()` functions to let the cat do the following:
// 1. Walk from `startPos` to `centerPos`.
// 2. Then dance for 5 secs.
// 3. Then walk from `centerPos` to `stopPos`.
// 4. Repeat the first three steps indefinitely.
while (true) {
await walk(img, startPos, centerPos);
await dance(img);
await walk(img, centerPos, stopPos);
}
}

window.addEventListener('load', catWalk);