0

I'm creating an examination application and I want users to prevent page reload while attending the examination because it refreshes the examination timer too. Is there any way to directly avoid page reload in Javascript or Can anyone suggest another ideal way of doing it like showing popup and avoiding page reload or something?

1 Answers1

1

You can't really prevent the user from reloading, as it is a default behavior of the browser, what you can do is store the timer value somewhere (a backend server or localstorage) and then fetch the value from there during each session

// you cannot run this snippet here because of stack security reasons
let timerValue = localStorage.getItem('timer') || 10; // if timer value is not found then it should be 10 seconds by default

const wait = (ms) => new Promise(r => setTimeout(r, ms));

run();

async function run() {
    console.log('timer has begun');
    while(true) {
        if (timerValue <= 0) break;
        timerValue--;
        localStorage.setItem('timer', timerValue);
        await wait(1000);
    }

    console.log('timer has ended');
    localStorage.setItem('timer', null); // reset timer once the test is finished
}

Note: this is just a temporary solution, a better one would be to set up a express server as your backed and use it to serve the timer values on each session

AnanthDev
  • 1,605
  • 1
  • 4
  • 14