-
Notifications
You must be signed in to change notification settings - Fork 108
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
//用js写一个简单的交通灯功能,10秒绿灯倒数,3秒黄灯倒数,5秒红灯倒数,如何让三个灯不断交替重复? | ||
function red() { | ||
console.log('red light'); | ||
} | ||
|
||
function green() { | ||
console.log('green light'); | ||
} | ||
|
||
function yellow() { | ||
console.log('yellow light'); | ||
} | ||
function tick(timer, callback){ | ||
return new Promise((resolve, reject) => { | ||
setTimeout(() => { | ||
callback(); | ||
resolve(); | ||
}, timer); | ||
}); | ||
} | ||
var promise = new Promise((resolve, reject) => { | ||
resolve() | ||
}); | ||
function loop() { | ||
promise.then(() => { | ||
return tick(10000, green); | ||
}).then(() => { | ||
return tick(3000, yellow); | ||
}).then(() => { | ||
return tick(5000, red); | ||
}).then(() => { | ||
loop(); | ||
}); | ||
} | ||
loop(); |