Set exam time 30 minutes by Javascript error? - javascript

I am writing for web exam page ,in there I have to set 30 minutes to exam time.So I used onload and settimeout function to check if 30 minutes over,the question page is close and go to finish page.I want to add current minutes 30.But it's doesn't work,don't go to finish.php.!
<body onload="time()">
<!-- question code -->
<div id="time"></div><!-- show time -->
</body>
JS
<script>
function time(){
var j = new Date();
var hr = j.getHours();
var sec = j.getSeconds();
var min = j.getMinutes();
var m = min + 30;//set 30 minutes exam times
if (m === min) {
location.href = "finish.php";
}
document.getElementById('time').innerHTML = hr + ":" + min + ":" + sec;
setTimeout(function() {
time()
}, 1000);
}
</script>

Try with this
function time(){
setTimeout(function() {
location.href = "finish.php";
}, 30*60*1000);
setInterval(function() {
var j = new Date();
var hr = j.getHours();
var min = j.getMinutes();
var sec = j.getSeconds();
document.getElementById('time').innerHTML = hr + ":" + min + ":" + sec;
}, 1000);
}

function time() {
var time = 60 * 1; //Replace 1 with 30 minutes
var minutes, seconds;
setInterval(function () {
minutes = parseInt(time / 60)
seconds = parseInt(time % 60);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById('time').innerHTML = minutes + ":" + seconds;
time--;
if (time < 0) {
location.href = "finish.php";
}
}, 1000);
}
<body onload="time()">
<!-- question code -->
<div id="time"></div><!-- show time -->
</body>

Your are assigning new value to m every timeout. you should initialize, m only once.
also minute goes from 0-59 so you cant always check for it is equal to m + 30, thats wrong way of doing it
being said that its always better to do this timeout at server side, at client side there are enough ways to cheat around it

Related

Turn Javascript localStorage countdown timer into an animated Progress Bar

I was searching for a sitewide javascript timer, which does not reset when a page is changed, and I have stumbled onto this one, along with its demo.
This could be a stupid question, but I was wondering if this "minutes : seconds" timer format could be turned into an animated progress bar type of countdown, meaning that as the time passes, the bar should get smaller.
Here is the code I am currently using:
<div id="time"></div>
<script>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + " " + " " + seconds;
if (--timer < 0) {
timer = duration;
}
console.log(parseInt(seconds))
window.localStorage.setItem("seconds",seconds)
window.localStorage.setItem("minutes",minutes)
}, 1000);
}
window.onload = function () {
sec = parseInt(window.localStorage.getItem("seconds"))
min = parseInt(window.localStorage.getItem("minutes"))
if (parseInt(min*sec)) {
var fiveMinutes = (parseInt(min*60)+sec);
} else{
var fiveMinutes = 60 * 45;
}
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
</script>
Any ideas?

Hiding div classes when timer ends in Javascript

I have a timer script but I am having a few issues with it. Just a day ago, it was working perfectly fine, as intended. Now, the timer no longer hides the div class when it ends. Didn't change the HTML or JavaScript code at all, but for whatever reason it no longer removes the div class.
Here is the JavaScript code:
function startTimer(duration, display) {
var timer = duration,
minutes,
seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
display.textContent = minutes + ' ' + ' ' + seconds;
if (--timer < 0) {
display.textContent = 'OFFER HAS EXPIRED.';
$('.formme').css('visibility', 'hidden');
}
console.log(parseInt(seconds));
window.localStorage.setItem('seconds', seconds);
window.localStorage.setItem('minutes', minutes);
}, 1000);
}
window.onload = function() {
sec = parseInt(window.localStorage.getItem('seconds'));
min = parseInt(window.localStorage.getItem('minutes'));
if (parseInt(sec) == 0 && parseInt(min) == 0) {
$('#time').text('OFFER HAS EXPIRED.');
$('.formme').css('visibility', 'hidden');
} else {
var start = 5 * 60;
if (sec > 0 || min > 0) {
start = parseInt(min * 60) + sec;
}
// var start = 60 * 5;
display = document.querySelector('#time');
startTimer(start, display);
}
};
On top of that, I used localStorage to prevent the timer from resetting when the webpage is refreshed. However, when the timer is finished, instead of going straight to the "OFFER HAS EXPIRED" text, it counts down from 00:01 then displays the text. Can anyone help me out? Thanks in advance!

How to prevent countdown timer from resetting when webpage is refreshed?

I am designing a website and I integrated a 5 minute countdown timer that starts when the web-page is loaded, using JavaScript. However, since I am more of a designer than a developer, I don't know how to edit the JavaScript code to make it so that the timer does not restart when the webpage is reloaded. I know I have to store the users cookies, and I've searched online, but the javascript code didnt work when I inserted the code. Would anyone here be able to help me out? Thank you!
Here is the javascript code for the 5 minute timer:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + " " + " " + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
Check this approach where the time is stored in local storage of the browser and hence on refresh will not reset:
:HTML CODE:
<div id="time">
</div>
:JS CODE:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + " " + " " + seconds;
if (--timer < 0) {
timer = duration;
}
console.log(parseInt(seconds))
window.localStorage.setItem("seconds",seconds)
window.localStorage.setItem("minutes",minutes)
}, 1000);
}
window.onload = function () {
sec = parseInt(window.localStorage.getItem("seconds"))
min = parseInt(window.localStorage.getItem("minutes"))
if(parseInt(min*sec)){
var fiveMinutes = (parseInt(min*60)+sec);
}else{
var fiveMinutes = 60 * 5;
}
// var fiveMinutes = 60 * 5;
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
Here is the working model of the same in the codepen https://codepen.io/anon/pen/GymRNV?editors=1011
P.S: couldn't use it here as it is a sandbox and cant access localstorage.
You should use web "Session storage" api for this case. it will much help you.
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
sorry var distance = localStorage.getItem("mytime") - now;var x =localStorage.getItem("mytime"); I spent about 6 weeks figuring this out,it works,you need localstorage but only on countdown,now still has to function so counter counts,countdown is the anchor,look at w3school there countdown is set thats why it works,and thats were you use localstorage
use w3 school countdown timer,countdown date use localstorage.mytime=setDate(d.getDate + 7),also at end if distance < 0;localStorageremoveItem, thats it ,run code

How do you decrement time for minutes seconds hundredths?

Suppose you wanted to set a timer to whatever time you want will be displayed in the form 00:00:00 minutes, seconds, and hundredths. How would you go about doing so? Please any help is greatly appreciated.
Here is the link in JSFiddle:
https://jsfiddle.net/mxpuejvz/2/
function decrement(){
var time = 600;
var mins = parseInt((time / 100) / 60);
var secs = parseInt((time / 100) % 60);
var hundredths = parseInt(time % 100);
if(mins < 10) {
mins = "0" + mins;
}
if(secs < 10) {
secs = "0" + secs;
}
if(hundredths < 10) {
hundredths = "0" + hundredths;
}
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + hundredths;
if (hundredths === 0){
if(time ===0){
clearInterval(countdownTimer);
document.getElementById("output").innerHTML = "Time's Up.";
}else{
time--;
}
var countdownTimer = setInterval('decrement()', 10)
}
}
}
Three issues appear to need attention.
"time to go" needs to be stored outside the screen update function and decremented or calculated each time the screen is updated.
using parseInt to convert numbers to integer numbers is regarded as a hack by some. Math.floor() or integer calculation can be alternatives.
Timer call backs are not guaranteed to made exactly on time: counting the number of call backs for a 10msec time does not give the number of 1/100ths of elapsed time.
The following code is an example of how it could work, minus any pause button action.
var countdownTimer;
var endTime;
var counter = 0; // ** see reply item 3. **
function startCountDown( csecs) // hundredths of a second
{ endTime = Date.now() + 10*csecs; // endTime in millisecs
decrement();
countdownTimer = setInterval(decrement, 10);
counter = 0; // testing
}
function decrement()
{ var now, time, mins, secs, csecs, timeStr;
++ counter; // testing
now = Date.now();
if( now >= endTime)
{ time = 0;
timeStr = "Times up! counter = " + counter;
clearInterval( countdownTimer);
}
else
{ time = Math.floor( (endTime - now)/10); // unit = 1/100 sec
csecs = time%100;
time = (time-csecs)/100; // unit = 1 sec
secs = time % 60;
mins = (time-secs)/60; // unit = 60 secs
timeStr =
( (mins < 10) ? "0" + mins : mins) + ":" +
( (secs < 10) ? "0" + secs : secs) + ":" +
( (csecs < 10) ? "0" + csecs : csecs);
}
document.getElementById("output").innerHTML=timeStr;
}
The argument to startCountDown gives the number of 1/100ths of second for the count down. If the counter result is the same as the argument,try swapping browser tabs and back again during the countdown.
HTML to test:
<button type="button" onclick="startCountDown(600)">start</button>
<div id="output">
</div>

Get time split into minutes and seconds

I have the following code, which is supposed to do what I need:
function fromSeconds(seconds, showHours = false) {
if(showHours) {
var hours = Math.floor(seconds / 3600),
seconds = seconds - hours * 3600;
}
var minutes = (Math.floor(seconds/60) < 10) ?
"0" + Math.floor(seconds/60) : Math.floor(seconds/60);
var seconds = (seconds % 60 > 9) ? seconds % 60 : "0" + seconds % 60;
if(showHours) {
var timestring = hours + ":" + minutes + ":" + seconds;
} else {
var timestring = minutes + ":" + seconds;
}
return timestring;
}
The problems is that I also have this:
var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function() {
$('#currentTime').html(video[0].currentTime.toFixed(2));
$('#remTime').html((video[0].duration - video[0].currentTime).toFixed(2));
$('#totalTime').html(video[0].duration.toFixed(2));
});
And I don't know how to apply the first code so that for example currentTime is displayed like this: minutes:seconds.
Any help please?
With a small fixation you can leave this as that:
Demo
function fromSeconds(seconds, showHours) {
if(showHours) {
var hours = Math.floor(seconds / 3600),
seconds = seconds - hours * 3600;
}
var minutes = ("0" + Math.floor(seconds/60)).slice(-2);
var seconds = ("0" + parseInt(seconds%60,10)).slice(-2);
if(showHours) {
var timestring = hours + ":" + minutes + ":" + seconds;
} else {
var timestring = minutes + ":" + seconds;
}
return timestring;
}
var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function () {
$('#currentTime').html(fromSeconds(video[0].currentTime));
$('#remTime').html(fromSeconds(video[0].duration - video[0].currentTime));
$('#totalTime').html(fromSeconds(video[0].duration));
});
You can just pass the values like video[0].currentTime to the function fromSeconds which will return the formatted string
var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function () {
$('#currentTime').html(fromSeconds(video[0].currentTime));
$('#remTime').html(fromSeconds(video[0].duration - video[0].currentTime));
$('#totalTime').html(fromSeconds(video[0].duration));
});
Assuming currentTime is the time in seconds, you need to pass the value into your function.
fromSeconds returns the text your require, so fromSeconds(mytimevalue) will return mm:ss as required:
video.bind("timeupdate", function() {
$('#currentTime').html( fromSeconds(video[0].currentTime) );
$('#remTime').html( fromSeconds(video[0].duration - video[0].currentTime) );
$('#totalTime').html( fromSeconds(video[0].duration) );
});
Another option would be to use JavaScript's Date() Object, which takes milliseconds as a value:
var currentTime = new Date(video[0].currentTime * 1000);
You can then use Date.getMinutes() and Date.getSeconds() to find your values.
More details here
$('#currentTime').html(function(){
var time=video[0].currentTime.toFixed(2);
//some conversion needed in-order to convert to required format
fromSeconds(time,false)//returns time
});

Categories

Resources