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?

5
  • 1
    There is no way to prevent the user from reloading. Commented Oct 30, 2021 at 9:14
  • 2
    because it refreshes the examination timer too then you should fix that, instead of trying to mess around with the default behavior of a browser. Commented Oct 30, 2021 at 9:15
  • 1
    XY Problem - fix your timer. Ideally use server-side to store start-time. Commented Oct 30, 2021 at 9:19
  • 1
    You should save the the timer information on server to maintain the remaining time Commented Oct 30, 2021 at 9:31
  • Thanks everyone for your suggestions... Commented Oct 31, 2021 at 12:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.