Open vaakian opened 3 years ago
题目:令一个box的背景3秒红,1秒黄,2秒绿,如此循环往复。
<div id="box"></div> <button onclick="m.stop()">stop</button> <button onclick="m.restart()">restart</button> <style> #box { background-color: red; height: 100px; width: 100px; } </style> <script> const colors = [ { color: 'red', delay: 3000, },{ color: 'yellow', delay: 1000, },{ color: 'green', delay: 2000, } ] function Machine(el) { let timer = null let stoped = false return { stop() { if(!stoped) { clearTimeout(timer) stoped = true } }, start(i) { currentColor = colors[i%3] el.style.backgroundColor = currentColor.color if(!stoped) { timer = setTimeout(() => this.start(i+1), currentColor.delay) } }, restart() { if(stoped) { stoped = false this.start(0) } } } } const m = new Machine(document.getElementById("box")) m.start(0) </script>
jdhkfjsd