JSFiddle - React, Tailwind, and code Playground
Vanilla JS - Un Petit Exercise
by DarMontou
HTML
<body>
<div class="instructions">
<div class="important">
Before starting, fork this fiddle to get a new URL.
</div>
<div>
Once you've completed the exercise, send your new URL back to us.
</div>
</div>
<p>
Using vanilla Javascript or any frameworks in which you're proficient (add via <kbd>External Resources</kbd> at left), please print the numbers 1-10 at one-second intervals in the box below when <button id='myButton'>this button</button> is clicked.
</p>
<div class="box" id="myBox"></div>
<p class="considerations">Considerations</p>
<ul class="items">
<li>Are there ways to ensure a good user experience?</li>
<ul class="items">
<li>Disabling the button during countdown seems helpful.</li>
<li>A separate stop and/or reset button might be useful.</li>
<li>A consistent box size would be nicer.</li>
</ul>
<li>Would any ES6 features be useful in building this component?</li>
<ul>
<li>Arrow functions make anonymous function declarations convenient.</li>
<li>The template literal used for the box's innerHTML feels more concise than string concatenation, and for more advanced scenarios reduces the need for thinking about escape characters.</li>
<li>We could use a promise for the counting functionality.</li>
</ul>
</ul>
</body>
CSS
body {
padding: 1em;
font-family: sans-serif;
line-height: 1.4em;
}
.instructions {
text-align: center;
background: #049fd9;
padding: 1em;
color: #fff;
}
.important {
font-weight: bold;
}
.box {
border: 1px solid #858587;
padding: 1em;
border-radius: 5px;
}
.considerations {
font-weight: bold;
margin-bottom: 0.25em;
}
.items {
margin-top: 0;
}
JavaScript
function incrementer() {
const myBox = document.getElementById('myBox'),
myButton = document.getElementById('myButton')
myButton.disabled = true
let currentValue;
try {
currentValue = parseInt(myBox.childNodes[0].innerText)
if (currentValue === 10){
currentValue = 0
}
} catch(err) {
currentValue = 0
}
currentValue = currentValue + 1
myBox.innerHTML = `<p>${currentValue}</p>`
if (currentValue < 10) {
setTimeout(() => incrementer(), 1000)
} else {
myButton.disabled = false
}
}
document.getElementById('myButton').onclick = () => incrementer();