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?
Asked
Active
Viewed 671 times
0
-
1There is no way to prevent the user from reloading. – t.niese Oct 30 '21 at 09: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. – t.niese Oct 30 '21 at 09:15
-
1XY Problem - fix your timer. Ideally use server-side to store start-time. – freedomn-m Oct 30 '21 at 09:19
-
1You should save the the timer information on server to maintain the remaining time – Shahzaib Oct 30 '21 at 09:31
-
Thanks everyone for your suggestions... – prabath shalitha Oct 31 '21 at 12:34
1 Answers
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