I am building a quiz app in PHP using a MYSQL database of questions.
The app has a timer at the top which needs to maintain the correct timer value when the page
- moves to the next question in quiz
- The page is refreshed using F5
- The page is closed using Alt+F4 or the x button
- The back button is clicked
window.unload in javascript does not work for back button, closing of window.
I could not find any other solution, so went for the somewhat incorrect solution to storing the timer value every N seconds. So if user were to do any of above 4 activities, the timer would be off by Maximum N seconds. This requires me to UPDATE a MYSQL table every N seconds using ajax.
In the best case, N=1, which makes the site visibly slower.
N=3 works better, but I am not happy with it.
I use setinterval for running the ajax function every N seconds
Any suggestions here?
PLease suggest alternative methods to achieve my goal which are not database intensive. I am not a DB expert, so this might be trivial.
Short version of question
How do I get control to perform some action (eg, store something in a database) when the Back button is pressed or the page otherwise goes out of focus?
2
Answers
It is unclear what this "timer" does. Does it count down? Count up? What is its purpose? You clearly forgot to explain this.
Let’s say it’s a countdown timer, telling people how much time they have left to do the quiz. You give them 10 minutes, 600 seconds, and simply subtract one second, every second.
Now you need to keep track of every second, store that number somewhere, and update, what is stored, every second.
What if you stored only the time the quiz started? Say "2022-02-27 15:45:33". Then you know the timer will be down to zero at "2022-02-27 15:55:33". When it is "2022-02-27 15:48:03" you know that 2.5 minutes have passed: 150 seconds. The timer has 450 seconds left.
By using a fixed point in time, stored somewhere, you can compute a relative time, like a countdown timer, without having to store the value of the timer every second.
One solution to keep accurate track on time is using
http-header
.Still, will be some adjustments on logic.
Means:
so end page will mark the form as used and cannot be open again
header('Refresh: 60; https://end_test_for_user.php?id=123')
,id will be dynamically added