Created
January 16, 2024 04:36
-
-
Save xxiz/ff33aca56ad0f40a1e945f2cbe591b4a to your computer and use it in GitHub Desktop.
Ensure that your time is correct
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
// Function to display a clock | |
function displayClock() { | |
setInterval(() => { | |
const now = new Date(); | |
const hours = now.getHours().toString().padStart(2, '0'); | |
const minutes = now.getMinutes().toString().padStart(2, '0'); | |
const seconds = now.getSeconds().toString().padStart(2, '0'); | |
console.log(`${hours}:${minutes}:${seconds}`); | |
}, 1000); | |
} | |
// Unit test to check if displayed time is accurate | |
async function testDisplayClock() { | |
const response = await fetch('http://worldtimeapi.org/api/timezone/America/New_York'); | |
const data = await response.json(); | |
const time = data.datetime.slice(11, 19); | |
return new Promise((resolve, reject) => { | |
const timeoutId = setTimeout(() => { | |
clearTimeout(timeoutId); | |
reject(new Error('Test timed out.')); | |
}, 5000); | |
const intervalId = setInterval(() => { | |
const now = new Date(); | |
const hours = now.getHours().toString().padStart(2, '0'); | |
const minutes = now.getMinutes().toString().padStart(2, '0'); | |
const seconds = now.getSeconds().toString().padStart(2, '0'); | |
const displayedTime = `${hours}:${minutes}:${seconds}`; | |
if (displayedTime === time) { | |
clearInterval(intervalId); | |
clearTimeout(timeoutId); | |
resolve(); | |
} | |
}, 1000); | |
}); | |
} | |
// Call the displayClock function and run the test | |
displayClock(); | |
testDisplayClock().then(() => { | |
console.log('Test passed.'); | |
}).catch((error) => { | |
console.error('Test failed:', error.message); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment