The Traffic Light, On Time چالش 6 از جلسهی 34، سخت
چراغ راهنما را با زمانبندی درست روشن کن. wait آماده است. از صفر بنویس:
۱. تابع async به اسم turn(id: string, ms: number): Promise<void>: چراغی را که این id را دارد روشن میکند (کلاس on)، به اندازهی ms صبر میکند و خاموشش میکند. اگر چراغ پیدا نشد، هیچ کاری نمیکند.
۲. تابع async به اسم press(): Promise<void> که به ترتیب این کارها را میکند:
- red برای 2000
- green برای 2000
- yellow برای 1000
- و آخر در #msg مینویسد Done
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
.traffic { width: 70px; margin: 12px auto; padding: 10px; border-radius: 16px; background: #1e293b; }
.light { width: 50px; height: 50px; margin: 8px auto; border-radius: 50%; background: #64748b; }
#red.on { background: red; }
#yellow.on { background: gold; }
#green.on { background: limegreen; }
</style>
<div class="traffic">
<div id="red" class="light"></div>
<div id="yellow" class="light"></div>
<div id="green" class="light"></div>
</div>
<button id="go" onclick="press()">Start</button>
<p id="msg"></p>
<script type="text/typescript">
function wait(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// 1. async function turn
// 2. async function press
</script>
راهنما و جواب این چالش · برگشت به درس جلسهی 34: بعداً، با نوع
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js