<html> <body> <div id='lock'></div> <script> const lock = document.getElementById('lock') function makeLockDigit(changeCallback) { // Make an input that can be set between 0 and 9. // This is equivalent to <input type='number' min='0' max='9' />. const digit = document.createElement('input') digit.type = 'number' digit.min = 0 digit.max = 9 // Start it with a random value digit.value = String(Math.floor(Math.random() * 10)) // When the digit changes, call `changeCallback()`, // passing the new value of the digit. // Inputs' values are strings, so we convert them to numbers. digit.addEventListener('change', () => { changeCallback(Number(digit.value)) }) // Add the digit to the lock lock.appendChild(digit) } // The super secret combination const COMBO = [1, 2, 3, 4] // The number of correct digits let correctCount = 0 for (let i = 0; i < 4; i++) { // Whether this digit was previously correct let wasCorrect = false makeLockDigit(value => { // Compare the digit's actual value to the correct value const isCorrect = (value === COMBO[i]) // Update the number of correct digits if this one changed if (!wasCorrect && isCorrect) correctCount++ else if (wasCorrect && !isCorrect) correctCount-- wasCorrect = isCorrect // If all digits are now correct, show a message if (correctCount === COMBO.length) { alert('You got the combination') } }) } </script> </body> </html>