From 61660820c2cfbb18a3d84f773b4d7347d9e726b4 Mon Sep 17 00:00:00 2001 From: starshynova Date: Wed, 30 Oct 2024 12:06:46 +0100 Subject: [PATCH] API w1 finished prep-exercise --- .../1-catwalk-promises/index.js | 40 ++++++++++++------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/Week1/prep-exercises/1-catwalk-promises/index.js b/Week1/prep-exercises/1-catwalk-promises/index.js index dc07a9fe..3664dc8f 100644 --- a/Week1/prep-exercises/1-catwalk-promises/index.js +++ b/Week1/prep-exercises/1-catwalk-promises/index.js @@ -1,5 +1,4 @@ 'use strict'; - const STEP_SIZE_PX = 10; const STEP_INTERVAL_MS = 50; const DANCE_TIME_MS = 5000; @@ -7,20 +6,29 @@ const DANCING_CAT_URL = 'https://media1.tenor.com/images/2de63e950fb254920054f9bd081e8157/tenor.gif'; function walk(img, startPos, stopPos) { + img.style.left = startPos + 'px'; + let currentLeftPos = startPos; 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. + function catMoving () { + currentLeftPos = currentLeftPos + STEP_SIZE_PX; + img.style.left = currentLeftPos +'px'; + + if (currentLeftPos <= stopPos) { + setTimeout(catMoving, STEP_INTERVAL_MS) + } else {resolve();} + } + catMoving(); }); } 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. + img.src = DANCING_CAT_URL; + setTimeout(() => { + img.src = + 'http://www.anniemation.com/clip_art/images/cat-walk.gif'; + resolve(); + }, DANCE_TIME_MS); }); } @@ -30,11 +38,13 @@ function catWalk() { 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. + function walkingCat() { + walk(img, startPos, centerPos) + .then(() => dance(img)) + .then(() => walk(img, centerPos,stopPos)) + .then(walkingCat) + } + walkingCat(); } -window.addEventListener('load', catWalk); \ No newline at end of file +window.addEventListener('load', catWalk);