I wanna to create a timedown with mongoose and excited an function at the end of time. I have a quiz and I wanna at the end of time logout from quiz page. code implemented with nodejs
CodePudding user response:
You can try this:
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2022 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days "d " hours "h "
minutes "m " seconds "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
This is an example of js timedown for js/dom. and you can easily change the document.getElementById() by any var you want.
CodePudding user response:
I would say to create a token (jwt) including the timestamp of the quiz starts on the server, user_id, and quiz_id and pass it to the client application. Then you might tick the timer in the ejs app itself using the native js function setInterval()
and can automatically trigger an exit from the quiz page when ticker time reaches the quiz expiry time.
For each answer submission, you may pass that token created on quiz initiation to the server alongside submission details, so that server can validate whether that token is still valid to use (based on the quiz expiry time). So by the time expires, the server will no longer accept answers for that particular quiz since the token gets expired.
You may include the business logic based on your needs, this is a more generic answer for your generic question. (This might not be the best way of implementing a quiz, but this works with minimal server requests.)