View:
<div class="box-body">
<h2><p style="float: right" id="countdown"></p></h2>
</div>
<script>
$time_limit = $("#time_limit").val(); //2016-08-14 00:10:00
var d = new Date($time_limit);
var hours = d.getHours(); //00 hours
var minutes = d.getMinutes(); //10 minutes
var seconds = 60 * minutes; // 600seconds
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
console.log(minutes);
var hours = Math.round((minutes) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(myVar);
document.getElementById('countdown').innerHTML = "Time Out";
} else {
seconds--;
console.log(seconds);
}
}
var myVar = setInterval(secondPassed, 1000);
</script>
MY Question: When i browser page refresh and countdown timer should not continue, i click next button and browser page refresh and countdown timer should not continue .......................................................
if (typeof(Storage) == "undefined")
{
alert("Your browser does not support web storage");
//Abort the script;
//throw new Error("Something went badly wrong!");
}
$time_limit = $("#time_limit").val();
var d = new Date($time_limit);
var hours = d.getHours(); //00 hours
var minutes = d.getMinutes(); //10 minutes
var seconds = 60 * minutes;
if (localStorage.getItem("seconds") !== null)
{
seconds = localStorage.getItem("seconds");
}
function secondPassed()
{
var minutes = Math.round((seconds - 30) / 60);
console.log(minutes);
var hours = Math.round((minutes) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(myVar);
document.getElementById('countdown').innerHTML = "Time Out";
} else {
seconds--;
console.log(seconds);
}
localStorage.setItem("seconds",seconds);
}
var myVar = setInterval(secondPassed, 1000);
If you need persistance for this case you need to save the data in to the localstorage for the browser, because otherwise it always gets cleared after a refresh. I´ve prepared an example. You can find it here:
Countdown with Storage
The necessary Code pieces are the following:
if (typeof(Storage) !== "undefined") { // checks if localStorage is enabled
if (localStorage.seconds) { // checks if seconds are saved to localstorage
seconds = localStorage.seconds; // grabs the data from localstorage
}
}
With this piece of code you get the data initially from the localstorage. I´ve placed it above your function so it gets invoked imediately after setting everything for startup.
The other part is, to save the data. This piece of code is responsible for this purpose:
if (typeof(Storage) !== "undefined") {
localStorage.setItem("seconds", seconds);
}
You again check if the Storage is available for you and then you set seconds to the disred value.
The last step is to clear the localstorage after the time has expired:
if (typeof(Storage) !== "undefined") {
localStorage.removeItem("seconds");
}
Again, checking if Storage exists and then remove the item with the name seconds. Another possibility would be to check one time if Storage exists and either tell the user that the data is not persistet or work with cookies.
Related
I have found a code but i dont know to add timezone . i want to detect the timer from the timezone of the other country like denmark/copenhagen. thank you. this is my code.
<script type="text/javascript">
ElapsedTimeLogger = function(dateElementId, elapsedElementId, hiden, interval) {
var container = $(elapsedElementId);
var time = parseDate($(dateElementId).val());
var interval = interval;
var timer;
function parseDate(dateString) {
var date = new Date(dateString);
return date.getTime();
}
function update() {
var systemTime = new Date().getTime();
elapsedTime = systemTime - time;
container.html(prettyPrintTime(Math.floor(elapsedTime / 1000)));
$(hiden).val(prettyPrintTime(Math.floor(elapsedTime / 1000)));
}
function prettyPrintTime(numSeconds) {
var hours = Math.floor(numSeconds / 3600);
var minutes = Math.floor((numSeconds - (hours * 3600)) / 60);
var seconds = numSeconds - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = hours + ":" + minutes + ":" + seconds;
return time;
}
this.start = function() {
timer = setInterval(function() {update()}, interval * 1000);
}
this.stop = function() {
clearTimeout(timer);
}
}
$(document).ready(function () {
var timeLogger = new ElapsedTimeLogger("#date", "#elapsed","#stoppedid", 1);
timeLogger.start();
$("#confirm").click(function() { //Stop timer upon clicking the Confirm Button
timeLogger.stop();
});
});
</script>
thank you. i dont know javascript. i know php only. i tried to put
before the code is running. i already save a time from europe/copenhagen. but when the timer is running. it says 6:00:01 abd counting.. but i want to run like this 0:00:01 and counting. and my idea the time from europe and time in my country is 6 hours. i want to run the time from europe not my country. because i save the time from europe using php. see bellow the code for save the time.
date_default_timezone_set("Europe/Copenhagen");
but wont work. i didnt found the solution
Analyzing this code, I rewrote the needed HTML to see what the code do. It's simply creates a counter in format hh:mm:ss and shows on screen, this counter show the time passed since the date informed.
to add the user timezone to reflect in your timer, you just need to recalculate the seconds inside the prettyPrintTime(numSeconds) function before use it to get hours, minutes and seconds.
function prettyPrintTime(numSeconds) {
var tzOffset = new Date().getTimezoneOffset(); // get the timezone in minutes
tzOffset = tzOffset * 60; // convert minutes to seconds
numSeconds -= tzOffset; // recalculate the time using timezone
var hours = Math.floor(numSeconds / 3600);
var minutes = Math.floor((numSeconds - (hours * 3600)) / 60);
var seconds = numSeconds - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = hours + ":" + minutes + ":" + seconds;
return time;
}
Take a look at the working code:
https://jsfiddle.net/4c6xdcpr/
function getClientTimeZone() {
var offset = new Date().getTimezoneOffset(),
o = Math.abs(offset);
return (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + ":" + ("00" + (o % 60)).slice(-2);
}
// Display Output
alert(getClientTimeZone());
I am creating an online examination system.
I click the Apply button, then the countdown timer starts. Some time later, the browser page closes. After I click the same exam name, the countdown timer continues from where it left off, but I want the time to start over from the beginning. Please see the screenshots below:
View:
<h2><p style="float: right" id="countdown"></p></h2>
Apply
<script>
$(document).ready(function () {
$examination_test_id = $("#examination_test_id").val();
$time_limit = $("#time_limit").val();
var d = new Date($time_limit);
var hours = d.getHours();
var minute = d.getMinutes();
var minutes = hours * 60 + minute;
var seconds = 60 * minutes;
if (typeof (Storage) !== "undefined") {
if (sessionStorage.seconds) {
seconds = sessionStorage.seconds;
}
}
function secondPassed() {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor((seconds - (hours * 3600)) / 60);
// var remainingSeconds = seconds - (hours * 3600) - (minutes * 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (typeof (Storage) !== "undefined") {
sessionStorage.setItem("seconds", seconds);
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(myVar);
document.getElementById('countdown').innerHTML = alert('Timeout');
window.location.href = base_url + "student/Examinations/check_answer/" + $examination_test_id;
if (typeof (Storage) !== "undefined") {
sessionStorage.removeItem("seconds");
}
} else {
seconds--;
}
}
var myVar = setInterval(secondPassed, 1000);
});
function resetCountdownInLocalStorage() {
sessionStorage.removeItem("seconds");
}
</script>
It may depends on browser, according to this link
The lifetime of a browsing context can be unrelated to the lifetime of
the actual user agent process itself, as the user agent may support
resuming sessions after a restart.
You may have to clean session stroage on tab close I think.
I have created an online examination system and I have put a countdown timer in online examination system. Below is my javascript code. Plz check
<h2><p style="float: right" id="countdown"></p></h2>
<script>
$(document).ready(function () {
$examination_test_id = $("#examination_test_id").val();
$time_limit = $("#time_limit").val();
var d = new Date($time_limit); //14-August-2016 01:20:00
var hours = d.getHours(); //01
var minute = d.getMinutes(); //20
var minutes = hours * 60 + minute;
var seconds = 60 * minutes; //00
console.log(seconds);
if (typeof (Storage) !== "undefined") { //checks if localStorage is enabled
if (sessionStorage.seconds) { //checks if seconds are saved to localstorage
seconds = sessionStorage.seconds;
}
}
function secondPassed() {
var minutes = parseInt((seconds) / 60);
var hours = parseInt(minutes / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
if (typeof (Storage) !== "undefined") {
sessionStorage.setItem("seconds", seconds);
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(myVar);
document.getElementById('countdown').innerHTML = alert('Timeout');
window.location.href = base_url + "student/Examinations/check_answer/" + $examination_test_id;
if (typeof (Storage) !== "undefined") {
sessionStorage.removeItem("seconds");
}
} else {
seconds--;
}
}
var myVar = setInterval(secondPassed, 1000);
});
});
</script>
MY Question: coundown timer should start at 01:20:00 ,but in my case, countdown timer starts at 01:80:00 , why? please check my javascript code
var minutes = hours * 60 + minute;
One hour and twenty minutes is 80 minutes in total. You should change that line to just have var minutes = minute;
In minutes, you are taking the total,
var minutes = hours * 60 + minute;
80= 1*60 + 20
in less than 5 seconds i just found an answer: Javascript return number of days,hours,minutes,seconds between two dates
or JavaScript seconds to time string with format hh:mm:ss
So please just search a little bit before posting this kind of question
// This timer keeps reseting back to 2:00 after it reaches 1 minute. Also i do not get a notification that says times up at the right time. Can someone please correct the code. Also the stop/resume timer button also has to stay functional.
var isRunning = false;
var ticker; //this will hold our setTimeout
var seconds,
minutes;
function countdown(mins, secs) {
//i made these global, so we can restart the timer later
seconds = secs || 60; //if user put in a number of minutes, use that. Otherwise, use 60
minutes = mins;
console.log('time stuff',mins,secs,minutes,seconds)
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if (seconds < 1 && minutes) {
//seconds reached 0, and still minutes left;
seconds=60;
minutes--;
}
if ((seconds > 0 || minutes > 0) && isRunning) {
ticker = setTimeout(tick, 1000);
} else if(isRunning){
console.log(seconds,minutes,isRunning)
alert('Time\'s up, brah!')
}
}
tick();
}
function timeToggle() {
isRunning = !isRunning; //if it's false, set it true. If it's true, set it false.
if (!isRunning) {
clearTimeout(ticker); //or whatever else you set the initial timeOut to.
} else {
//not running! and time is defined;
var sec = seconds||60;
console.log('def!',minutes, sec)
countdown(minutes, sec);
}
}
isRunning = true;
countdown(2);
<div id="timer">2:00</div>
<button onclick="timeToggle()">Stop time</button>
There is a small flaw in your logic.
During the countdown initialization your doing
seconds = secs || 60;
Which effectively add 60 seconds to the time you want if you don't initialize the seconds. see:
function countdownInit(mins, secs) {
seconds = secs || 60;
minutes = mins;
console.log(mins + 'min ' + seconds + 'sec');
}
countdownInit(1, 30) // ok
// 1min 30sec
countdownInit(1) // not ok
// 1min 60sec
// thats 2 minutes
The second issue here is that you use a var current_minutes that equals minutes - 1 to display the time. So you are not showing the real counter.
the fix is as follow:
function countdown(mins, secs) {
seconds = secs;
minutes = mins;
// if secs is 0 or uninitialized we set seconds to 60 and decrement the minutes
if(!secs) {
minutes--;
seconds = 60;
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
// we use minutes instead of current_minutes in order to show what's really in our variables
counter.innerHTML =
minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
// rest of code
}
// rest of code
}
I tried to keep as much as your code as possible.
We have a 24 hour countdown timer. Problem is, whenever the page is refreshed the timer restarts. How can we create a cookie so it doesn't restart for the same user/when refreshed? And if if goes down to 0 restarts again?
What we have so far:
<script type = "text/javascript">
var totalSeconds;
function initiate(seconds)
{
totalSeconds = parseInt(seconds);
setInterval("timeUpdate()", 1000);
}
function timeUpdate()
{
var seconds = totalSeconds;
if(seconds > 0)
{
totalSeconds--;
var hours= Math.floor(seconds/3600);
seconds %= 3600;
var minutes = Math.floor(seconds/60);
seconds %= 60;
var timeIs = ((hours < 10) ? "0" : "") + hours + ":" + ((minutes < 10) ? "0" : "") + minutes + ":" + ((seconds < 10) ? "0" : "") + seconds;
document.getElementById("timeLeft").innerHTML = "" + timeIs;
}
else
{
document.getElementById("timeLeft").innerHTML = '';
document.getElementById("message").innerHTML = '';
}
}
initiate(24 * 60 * 60);
</script>
document.cookie="name=" + cookievalue;
alert("Setting Cookies : " + "name=" + cookievalue );
SEE HERE
First we need to have functions to set and read cookies. For this use the functions given in this answer How do I create and read a value from cookie?
So, we have two functions createCookie and setCookie in our code.
Now set and get cookie on page load as given below
var
//Get time started
timeStarted = getCookie('timeStarted'),
//To store total seconds left
totalSeconds,
//Current Time
currentTime = parseInt(new Date()/1000),
//Timer Length
timerLength = 24 * 60 * 60;
if(timeStarted == "") {
//Time not yet started. Start now.
createCookie('timeStarted', currentTime, 365);
//We started time just now. So, we have full timer length remaining
totalSeconds = timerLength;
} else {
//Calculate total seconds remaining
totalSeconds = timerLength - (currentTime - timeStarted)%(timerLength);
}
Now initialize as given below
initialize(totalSeconds);
Both your functions work fine and keep them.
I used 365 days as the cookie period. We just need the start time.
Change the code as per your requirements.
Let me know if you need any clarification about this code.