-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathindex.js
More file actions
84 lines (60 loc) · 2 KB
/
index.js
File metadata and controls
84 lines (60 loc) · 2 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict';
const STEP_SIZE_PX = 10;
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) => {
let interval;
let catPos = startPos ;
interval = setInterval(()=>{
catPos += STEP_SIZE_PX;
img.style.left =catPos + 'px';
if(catPos >= stopPos){
clearInterval(interval);
resolve(catPos);
}
},STEP_INTERVAL_MS);
// setInterval(walk(img, startPos, stopPos),STEP_INTERVAL_MS);
// 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 dance(img) {
return new Promise((resolve) => {
img.src = DANCING_CAT_URL;
setTimeout(()=>{
img.src = WALKING_CAT_URL;
resolve();
}, DANCE_TIME_MS );
// 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.
});
}
function catWalk() {
const img = document.querySelector('img');
const startPos = -img.width;
const centerPos = (window.innerWidth - img.width) / 2;
const stopPos = window.innerWidth;
img.style.left = startPos +'px';
walk(img,startPos,centerPos).then((result) => {
dance(img).then(()=> {
walk(img,result,stopPos).then(()=> {
catWalk();
} );
});
}
)
// 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.
}
window.addEventListener('load', catWalk);