0
When we are playing a quiz there is timer running for every question. How can we create this type of timer using javascript?
2 Respostas
+ 5
This is mostly a conceptual answer so that others can deliver code / work with it / use another idea.
JS is event-driven, and only updates the DOM/display when you give up the main thread, so strategies used in other languages (like a tight loop waiting for the time to change, or sleeping for 1 second) would just hang the browser. In JS, if you want something to happen later, send a message using the event system, then drop off the end of your function so events run.
// onload is an event!
document.onload = function {
// set a message 1000ms from now
setTimeout(updateCounter, 1000);
// give up control, events will run
}
// Nothing happens in your code for 1000ms (the engine is busy handling events though)
// JS fires your event 1000ms later and runs this function
function updateCounter() {
...decrement the counter
...update a DOM element
if the counter is above 0:
setTimeout(updateCounter, 1000)
// give up control, events will run again
}