I an a newbie to JS and We created a code for clock that start from end time when reload a same page or moves to next page But this is not working properly. I am showing javascript code of that here . We are adding this to limesurvey js file.
Js code:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(window.location.href) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds ;
if (diff <= 0) {
display.textContent ="Time finished ";
alert("Time is over.Click ok to submit Exam.")
$("#movesubmitbtn").click();
clearInterval(handle);
}
}
// we don't want to wait a full second before the timer starts
timer();
var handle = setInterval(timer, 1000);
}
window.onload = function(){
//set cookie if not exist
if(document.cookie && document.cookie.match('examDuration')){
examTime = document.cookie.match(/(^|;)examDuration=([^;]+)/)[2];
}
else{
timeLimit = getURLParameter('examTime');
document.cookie = 'examDuration='+ 60*timeLimit + '; path=/; ' ;
examTime= 60*timeLimit ;
}
var display = document.querySelector('#time');
startTimer(examTime, display);
$("#movenextbtn").onclick(function(){
remainingTime = (minutes * 60) + seconds ;
document.cookie = 'examDuration='+ remainingTime + '; path=/; ' ;
clearInterval(handle);
});
$("#movesubmitbtn").onclick(function(){
remainingTime = (minutes * 60) + seconds ;
document.cookie = 'examDuration='+ remainingTime + '; path=/; ' ;
clearInterval(handle);
});
};
I don't know why it is not working. I have included JS library link in header of that and have taken all necessary steps were needed. Thanks in advance.
Related
I want to implement a counterdown which will show how much time left for session expire. If user performe some like CRUD operation then counterdown will be reset. If user is not performing any action then counter will stop at 0 second. I am not doing logout or session expire. I want to show counterdown only. Thanks.
I tried below code but it is hardcode 30 minutes. I dont want to hardcode.
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function ()
{var thirtyMinutes = 60 * 30,display = document.querySelector('#time');startTimer(thirtyMinutes, display);};
I have ROR application and i added countdown timer to it .
The timer count from 15 to zero then disappear. What i'm doing is to prevent count again on refresh page , so , i stored start value in localStorage.
But i need to reset the value when user log out and start count again when login again, here is my code:
function startTimer(duration, display) {
var start = localStorage.getItem("start"),
diff,
minutes,
seconds;
var shown = false;
if (start === null) {
start = Date.now();
localStorage.setItem("start", start);
}
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
start = 0;
$('#testDiv').hide();
if (shown == false){
$('#congModal').modal('show');
shown = true;
}
}
}
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fifteenMinutes = 60 * 15,
display = document.querySelector('#time');
startTimer(fifteenMinutes, display);
};
and on view i have:
`%li.list-inline-item.g-mx-10--xl.g-font-size-16
#testDiv{"data-value" => "show"}
%span= "#{t('layouts.navbar.countdown.next_reward_in')}"
%span#time 15:00
= "#{t('layouts.navbar.countdown.minutes')}"
%i{"data-target" => "#congModal", "data-toggle" => "modal"} `
This solved the problem!
on js file:
`function cleanUp(){
localStorage.removeItem('start')
}`
on view:
%a{ "data-method" => "delete", href: destroy_user_session_path, onclick: "cleanUp();"}
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 have this countdown timer. For some reason it stops counting after one minute - it just stops.
If I count for 55 minutes it stops at 54:00
If I count for 2 minutes it stops at 1:00
Any ideas how do I fix that so it continues up to zero?
Here is the JSFiddle link: Countdown timer with cookies
And the JS code:
function countdown(minutes) {
var seconds = 60;
var mins = minutes;
if(getCookie("minutes")&&getCookie("seconds"))
{
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
}
function tick() {
var counter = document.getElementById("timer");
setCookie("minutes",mins,10)
setCookie("seconds",seconds,10)
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
//save the time in cookie
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
countdown(55);
I don't know why you are using the cookies here but, putting that aside, your problem seems to be the following lines:
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
In your code after you finished the first minute you call the countdown function again with a minute less. However, the lines above returns the minute variable back to its previous value. So you end up stuck in the same minute after one minute pass.
So, I assume, you need to get the time from the cookies only once (first time the countdown runs). You can use something like this:
var firstTime = true;
function countdown(minutes) {
var seconds = 60;
var mins = minutes;
if(firstTime && getCookie("minutes")&&getCookie("seconds"))
{
firstTime = false;
seconds = getCookie("seconds");
mins = getCookie("minutes");
}
...
Note that var is unnecessary in the if clause since you already
defined seconds and mins variables.
Code with day:hours:minute:second support.
Just add number of minutes into timer span.
For one day test, I entered 1440 minutes.
<html>
<body>
<span id="countdown" class="timer">1440</span>
<script type="text/javascript">
var first_time = true;
var countdownTimer;
var seconds = document.getElementById('countdown').innerHTML * 60;
//alert(seconds);
if(!isNaN(seconds) && seconds > 0 ) {
function timer() {
if(first_time) {
countdownTimer = setInterval('timer()', 1000);
first_time = false;
}
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = (days < 10 ? "0" : "") + days + ":" + (hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (remainingSeconds < 10 ? "0" : "") + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
timer()
//var countdownTimer = setInterval('timer()', 1000);
}
</script>
</body>
</html>
I finally managed to make my 24 hour non-date dependable countdown timer. The purpose of this is that the countdown starts every time someone visits the site. The problem is that when any unit (hours, mins, secs) reaches single digits values display them as such instead of the standard time format (9 minutes instead of 09 minutes, as it should). How can I implement a condition that if a value it's <= 9 it adds a 0 before it?
var count = 86400;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + ":" + minutes + ":" + seconds; // watch for spelling
}
<span id='timer'></span>
Create one function similar to following that does the job for you:
function makeMeTwoDigits(n){
return (n < 10 ? "0" : "") + n;
}
And before printing your numbers call this function:
document.getElementById("timer").innerHTML = makeMeTwoDigits(hours) + ":" + makeMeTwoDigits(minutes) + ":" + makeMeTwoDigits(seconds);
Explanation:
Like #rfornal said, we're checking if the number is less that 10 which means single digit, add '0' and return otherwise add nothing and return.
One point to observe is this won't work if the number is negative.
You can use universal pad function from How to output integers with leading zeros in JavaScript
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
and change your code to:
document.getElementById("timer").innerHTML = pad(hours,2) + ":" + pad(minutes,2) + ":" + pad(seconds,2);
Try ...
document.getElementById("timer").innerHTML
= (hours<10 ? "0" + hours : hours) + ":"
+ (minutes<10 ? "0" + minutes : minutes) + ":"
+ (seconds<10 ? "0" + seconds : seconds);
Basically, saying if the value is less than 10, place a "0"; else just the value. Another way of saying this is if condition ? then : else ...
An alternate route ... more code would be:
var t_hours, t_minutes, t_seconds;
if (hours<10) {
t_hours = "0" + hours;
} else {
t_hours = hours;
}
if (minutes<10) {
t_minutes = "0" + minutes;
} else {
t_minutes = minutes;
}
if (seconds<10) {
t_seconds = "0" + seconds;
} else {
t_seconds = seconds;
}
document.getElementById("timer").innerHTML
= t_hours + ":" t_minutes + ":" t_seconds;