I'm having a problem with the time limit coz when the page is reload/refresh the time limit reset.
P.S: I used this time limit to my online quiz program and I'm using a header location to move to next question.
HTML
<label id="time">1:00</label>
JAVASCRIPT
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;
localStorage.setItem('time_remaining_min', minutes);
localStorage.setItem('time_remaining_sec', seconds);
var minutes_left = localStorage.getItem('time_remaining_min');
var seconds_left = localStorage.getItem('time_remaining_sec');
display.text(minutes_left + ":" + seconds_left);
if (--timer < 0) {
//finished
}
}, 1000);
}
jQuery(function ($) {
var fiveMinutes = 60 * 5,
display = $('#time');
startTimer(fiveMinutes, display);
});
EDIT:
I tried to use local storage but didn't work
localStorage.setItem('time_remaining_min', minutes);
localStorage.setItem('time_remaining_sec', seconds);
var minutes_left = localStorage.getItem('time_remaining_min');
var seconds_left = localStorage.getItem('time_remaining_sec');
display.text(minutes_left + ":" + seconds_left);
Store timer value either in cookie or in local storage.
Not sure that you will ever be able to get around this with a page refresh. Maybe the better answer would be to not to the page reload, and use AJAX to do whatever you need to do.
You can store the time in a cookie.
//Set cookie
time_remaining = 200;
$.cookie('time_remaining', time_remaining);
//Retrieve cookie
time_remaining = $.cookie('time_remaining');
You should be able to easily implement the above into your code (Hint: whenever the timer decreases, save time remaining in a cookie).
Note that this isn't that secure, users can easily clear and modify cookies in their browser. If you're looking for something more secure you'll need to implement some backend functionality.
Related
The counter works properly but starts again after refresh
How can I continue after refreshing the counter?
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 duration = 60 * 2,
display = document.getElementById("timer");
startTimer(duration, display);
};
you can try and use localStorage.
localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session end.
for example:
localStorage.setItem("duration",60);
localStorage.getItem("duration"); //60
check out this documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Here's the scenario, I have a time that counts the time_taken by a user. What I want is to get the exact time_taken based from the timer. For example, a user take an exam, then after he/she take the exam, the time_taken will be submitted (e.g. 1hr 25mins 23secs). Please see my code below.
$(document).ready(function(){
var d;
setInterval(function(){
d = new Date();
dates = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
$('#timeTaken').val(dates);
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="timeTaken" value="">
Here is Fiddle for the solution
https://jsfiddle.net/djzsddz6/1/
Ans Solution is below:
$(document).ready(function(){
var seconds = 0, minutes = 0 , hours = 0;
setInterval(function(){
seconds++;
if(seconds == 60){
minutes++
seconds = 0;
}
if(minutes == 60){
hours++
minutes = 0;
}
console.log(hours, minutes, seconds);
$('#timeTaken').val(`${hours}:${minutes}:${seconds}`);
}, 1000);
});
I don't really see the point to use an input there, you can just display in a span and when the form gets submitted take the time elapsed and send it with other data. Anyways, this should work for you:
$(document).ready(function () {
var time_start = new Date();
setInterval(function () {
var time_end = new Date();
var time_diff = (time_end - time_start);
// hours
var hours = Math.floor(time_diff / 1000 / 60 / 60);
// minutes
time_diff = time_diff - hours * 1000 * 60 * 60;
var minutes = Math.floor(time_diff / 1000 / 60);
// seconds
time_diff = time_diff - minutes * 1000 * 60;
var seconds = Math.floor(time_diff / 1000);
renderTime(hours, minutes, seconds);
}, 1000);
});
function renderTime (hrs, min, sec) {
var str = convertTime(hrs) + ":" + convertTime(min) + ":" + convertTime(sec);
$("#timeTaken").val(str);
}
function convertTime (val) {
return val < 10 ? "0" + val : val;
}
What's going on here is we have the time_start which does not change and we have setInterval function that is triggered every second. There we create new Date object, and the subtract the static one from it, which returns the time difference in milliseconds. We do the weird Math.flooring and subtracting, so we can have hours, minutes and seconds as an integers (not floats). Then we use render function to display the time inside an desired element.
Why I think it's a better solution then the others are, is that if you want to handle the user's page refresh you just need to save one variable to cookie or something else and it will work regardless of the page refresh.
Handling the page refresh would look like (with cookie saved for 2 hrs):
function updateTimeCookie () {
var time_now = new Date()
var value = JSON.stringify(time_now);
var expires = time_now.setTime(time_now.getTime() + 7200);
$.cookie("timeStart", value, { expires: expires });
};
// to get Date object from cookie: new Date(JSON.parse($.cookie("timeStart")))
To use $.cookie() you must first include jQuery Cookie Plugin.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
Working fiddle without cookie: https://jsfiddle.net/qc3axmf4/1/
Working fiddle with cookie: https://jsfiddle.net/ta8bnzs0/2/
Rather than getting date at every second you can keep the counter in set interval which will updated at every second. At the time of submission you can perform division and modulus operation to get exact time taken
Example
$(document).ready(function(){
var timer =0;
setInterval(function(){
Timer +=1;
// Code for display in hr mm and ss
$('#timeTaken').val(dates);
}, 1000'
});
You can also convert second in time valueby using moment.js
Hope this helps you.
Happy coding
I've a problem when running this script for my JavaScript countdown (using this plugin). What it should do is take the starting time, the current time and the end time and display the remaining time.
If I set these values with normal numbers in epoch time everything works just fine, but my question is: How do I set the current time and the start to be the real current one so that the countdown will be dynamic?
I've found this line: Math.round(new Date().getTime()/1000.0);
But I don't know how to make it work, considering I'm running this script at the bottom of my HTML file, before the </html> tag.
This is the script:
<script>
$('.countdown').final_countdown({
start: '[amount Of Time]',
end: '[amount Of Time]',
now: '[amount Of Time]'
});
</script>
This is how I tried to solve it, but it's not working:
//get the current time in unix timestamp seconds
var seconds = Math.round(new Date().getTime()/1000.0);
var endTime = '1388461320';
$('.countdown').final_countdown({
start: '1362139200',
end: endTime,
now: seconds
});
It sounds like you would like to count down from the current time to some fixed point in the future.
The following example counts down and displays the time remaining from now (whenever now might be) to some random time stamp within the next minute.
function startTimer(futureTimeStamp, display) {
var diff;
(function timer() {
// how many seconds are between now and when the count down should end
diff = (futureTimeStamp - Date.now() / 1000) | 0;
if (diff >= 0) {
display(diff);
setTimeout(timer, 1000);
}
}());
}
// wait for the page to load.
window.onload = function() {
var element = document.querySelector('#time'),
now = Date.now() / 1000,
// some random time within the next minute
futureTimeStamp = Math.floor(now + (Math.random() * 60));
// format the display however you wish.
function display(diff) {
var minutes = (diff / 60) | 0,
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
element.innerHTML = minutes + ":" + seconds;
}
startTimer(futureTimeStamp, display);
};
<span id="time"></span>
Also Math.round(new Date().getTime()/1000.0); will give you the number of seconds since the epoch, however it may be a little disingenuous to round the number. I think you would be better served by taking the floor:
var timestamp = Math.floor(Date.now() / 1000)); is probably a better option.
In addition I am not sure why you need the start time, current time and end time. In order to find the remaining number of second you just need to know when the timer should end and the current time.
I am just learning html and css, and want to add javascript code that I found on here. This code basicly counts down from specific minute or second.
Here is the 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 + " minutes " + seconds + " seconds";
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 28.4,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
How could I use this code multiple times? With different time settings. All on same page ofcourse.
I have this code in countdown.js file, and it works great. But If I try to make "countdown2.js" etc, and use that, it wont work. I changed "#time" in code to "time2" etc, and did same in html code.
Sorry for bad explanation. I dont realy know javascript yet, as I havent started learning it quite yet. But I realy need countdown on my site to appear 5 times, each time with different time settings. And I can only display it once.
try this
window.onload = function () {
var timer1 = 60 * 28.4,
display1 = document.querySelector('#time1');
startTimer(timer1, display1);
var timer2 = 60 * 28.5,
display2 = document.querySelector('#time2');
startTimer(timer2, display2);
//... Continues
};
The output will be shown in tags with ids time1 and time2 respectively.
I'm following this example of a PHP session timer using an AJAX call to check the 'time'.
I would like to be able to display some kind of display for the user that is simply a javascript countdown timer such as:
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 length = 60 * 5,
display = document.querySelector('#time');
startTimer(length, display);
};
but with var length equal to the value specified at $_SESSION['timeOut'] = SomeNumber; in the php file.
How can I set these to be exactly in sync and be able to output the countdown to the screen? Or am I able to just utilize the php timing and not necessarily create a js timer?
you can get time of now measured by seconds using php function time() and then save it as time of login in your DB .every time user refresh the page.you must send him $_SESSION['timeOut'] + ($time_of_login) - time() wich returns how much seconds to reach time out
$time_of_login from DB
so php file will look like:
var length = <? echo $_SESSION['timeOut'] + ($time_of_login) - time(); ?>