当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Don't reset the timeout on refresh

问题描述:

I'm creating online exam kind of application and in my app

when user clicks on start button we are going to display timer for 3:00 minutes

using setTimeout(func,3*60*1000)

but when I refresh the page the timout function is resetting, how to stop this

how to do this , this is a must have feature in my app.

Javascript or jquery anything welcomes

网友答案:

If you need to achieve this in a foolproof way that the user can't tamper with, you'll have to set the timer serverside.

If it's not that important, then you can store the start-time in localStorage and, on page load, use that value to resume the timer from where it began.

var oldStartTime = localStorage.getItem('startTime');
var startTime = oldStartTime ? new Date(oldStartTime) : new Date();
localStorage.setItem('startTime', startTime);

// you can now use startTime to determine the remaining duration for setTimeout:

var elapsed = new Date() - startTime;
var duration = 180000 - elapsed;

setTimeout(myFunction, duration);

Since you said it's an exam though, I assume you want people to not be able to cheat. If that's the case then there is literally no way to do this with client-side Javascript alone. It is always possible for the user to "tamper" if it's occurring in their own browser.

分享给朋友:
您可能感兴趣的文章:
随机阅读: