How to get a countdown timer to restart - javascript

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.

Related

timezone javascript in my timer

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());

how to calculate hours,minutes,second using javascript

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

when refresh browser page and countdown timer should not continue

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.

How to push/play setTimeout function

I want to show clock with some difference . below given code is working fine for me. but i want to push and play this time whenever user want. i want to push and resume SetTimeout function .any one have any idea how to do that ?
$("#push").click(function () {
});
$("#play").click(function () {
show();
});
function show() {
var Digital = new Date();
var time2 = Digital.getTime();
var time1 = 1403517957984;
var diff = Math.abs(new Date(time2) - new Date(time1));
var seconds = Math.floor(diff / 1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
var hours = Math.floor(minutes / 60);
minutes = minutes % 60;
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
$('#worked_time').html(hours + ":" + minutes + ":" + seconds);
setTimeout("show()", 1000);
}
show();
This is a mix of the respond of #colburton and #TwiStar
Respond correctly to the answer
var isPlaying = true;
var toHandle = null;
$("#push").click(function () {
isPlaying = false;
if (toHandle !== null)
{
clearTimeout(toHandle);
toHandle = null;
}
});
$("#play").click(function () {
isPlaying = true;
show();
});
function show() {
if (isPlaying) {
toHandle = null;
var Digital = new Date();
var time2 = Digital.getTime();
var time1 = 1403517957984;
var diff = Math.abs(new Date(time2) - new Date(time1));
var seconds = Math.floor(diff / 1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
var hours = Math.floor(minutes / 60);
minutes = minutes % 60;
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
$('#worked_time').html(hours + ":" + minutes + ":" + seconds);
toHandle = setTimeout("show()", 1000);
}
}
show();
Save the handle to a variable:
var toHandle = null;
// start timeout
toHandle = setTimeout("show()", 1000);
Then you can cancel the timeout any time you want with:
// cancel timeout
if (toHandle) {
clearTimeout(toHandle);
toHandle = null;
}
Quick and dirty. Surround you show-function with an if which checks a "should i show the time"-flag:
var doShow = true;
$("#push").click(function () {
doShow = false;
});
$("#play").click(function () {
doShow = true;
show();
});
function show() {
if(doShow == true) {
var Digital = new Date();
var time2 = Digital.getTime();
var time1 = 1403517957984;
var diff = Math.abs(new Date(time2) - new Date(time1));
var seconds = Math.floor(diff / 1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
var hours = Math.floor(minutes / 60);
minutes = minutes % 60;
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
$('#worked_time').html(hours + ":" + minutes + ":" + seconds);
setTimeout("show()", 1000);
}
}
show();

Why is this JavaScript timer crashing my web page?

So I'm trying to put together a timer to count down to a specific time on a specific day. I found some code to work with online and adapted it to this
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time)
{
Timer = document.getElementByID(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
window.setTimeout("Tick()", 1000);
function Tick()
{
if (TotalSeconds <= 0)
{
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer()
{
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr + " until my birthday!";
}
function LeadingZero(Time)
{
return (Time < 10) ? "0" + Time : + Time;
}
When I start it up on my web page it crashes the page. I know the problem is not how I link it to the HTML because I tested this code on http://writecodeonline.com/javascript/ and it did not work there either. Any advice?

Categories