So I'm trying to do a refresh status in which if the page was refreshed under 5 minutes, it would say "Updated Just Now," and if it was updated over 5 minutes ago, it would say, "Updated Moments Ago." Below is my Javascript:
var startTime, endTime;
function start() {
startTime = performance.now();
};
function end() {
endTime = performance.now();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
var seconds = Math.round(timeDiff);
if (seconds < 10) {
time = "Updated Just Now";
} else {
time = "Updated Moments Ago";
}
document.getElementById("demo").innerHTML = time;
}
window.onload = start
window.onload = end
However, it is very buggy and sometimes doesn't work at all. Any help will be appreciated.
Unless I missed something, I think You can use setTimeout. Initially set the HTML to 'Updated just now'.
const timeout = 5 * 60 * 1000
const changeText = () => {
document.getElementById("counter").innerHTML = "Updated moments ago";
}
setTimeout(changeText, timeout)
sandbox
You can simply do this instead of doing that stuff.
/* Note That 1000 is equivalent of 1 seconds */
setTimeout(function(){
document.getElementById("demo").innerHTML = "Updated Just Now";
}, 30000); /* This value is equivalent of 30 seconds */
setTimeout(function(){
document.getElementById("demo").innerHTML = "Updated Moments Ago";
}, 300000); /* This value is equivalent of 5 minutes */
Related
I have a method which takes a while to execute and I want to calculate how much take the execution of method:
var start = Date.now();
execute();
var final = Date.now();
var diff = final - start;
var seconds = diff / 1000;
var minutes = 0;
var hours = 0;
while(seconds >= 60)
{
minutes++;
seconds = Math.round(seconds/60);
}
while(minutes >= 60) {
hours++;
minutes = Math.round(minutes/60);
}
But I don't get correct information for minutes and seconds. Where is my mistake ?
The method takes somewhere 1 minute and few seconds, but in log shows only 20-40 seconds..
startTime = Date.now();
execute();
endTime = Date.now();
totalSeconds = (endTime -startTime)/1000
hours = Math.floor(totalSeconds/3600)
minutes = Math.floor((totalSeconds%3600)/60)
seconds = Math.floor((totalSeconds%3600)%60)
console.log(hours, minutes, seconds)
In your code, instead of dividing seconds by 60, you should subtract it. If your total time was 300 secs, in first loop, you will have seconds updated to 5 while minutes will be updated to 1.
My timer starts on window load. After a visitor closes my website page the timer pauses. If the visitor opens the same page (with timer) after 10 hours, the timer starts from the same time where it had paused earlier.
I want to create a 3 hour timer that starts when website page is loaded and that keeps ticking in the background even if the visitor is not currently visiting my website page.
I wish to redirect the visitor to another page say "amazon.com" after this 3 hour timer has expired, if he visits the website AFTER 3 hours.
function countdown() {
time = parseInt(localStorage.time);
if(isNaN(time) || time > (38 * 60)) {
//alert("An error occured: time left variable is corrupted, resetting timer");
localStorage.time = 38 * 60;
countdown();
return null;
}
if(time <= 0) {
alert("Your Timer Has Run Out! We Still Got 2 Discount Copies Left, Hurry Up!");
return null;
}
var timers = document.getElementsByClassName('timeleft');
Array.prototype.forEach.call(timers, function(timer) {
timer.innerText = formatTime(time);
})
time--;
localStorage.time = time;
setTimeout('countdown()', 1000);
}
function formatTime(time) {
minutes = Math.floor(time / 60);
seconds = time - minutes * 60;
if(String(seconds).length == 1) {
return String(minutes) + ":0" + String(seconds);
}
return String(minutes) + ":" + String(seconds);
}
window.onload = function() {
countdown();
}
<font size="+34"><div class="timeleft"></div></font>
I think you can just store the start time in localStorage, and compare it to the current time whenever the page is loaded:
function startOrRedirect () {
const startTime = localStorage.getItem('startTime')
if (startTime) {
const date1 = new Date(parseInt(startTime))
const date2 = new Date()
const hours = Math.abs(date1 - date2) / 36e5;
if (hours >= 3) {
redirect()
}
} else {
localStorage.setItem('startTime', Date.now)
setTimeout(redirect, 1000 * 60 * 60)
}
}
function redirect () {
window.location = 'https://amazon.com'
}
window.onload = startOrRedirect
I'm trying to make a countdown using moment.js and jQuery. It's supposed to countdown to 12.00, and when it has passed 12.00, it should count down to 24.00 etc. So always count down the next 12 hours. It also has to be in UTC. This is what I have right now and it works fine, except when it has passed 12.00, it says "Timer done".
How can I achieve this in the best way?
var currentTime, endTime, timeDif;
currentTime = moment.now().format('X');
endTime = moment(moment.utc(12, "HH")).format('X');
function roundEndTimer() {
var Hours, Minutes, Seconds;
timeDif = endTime - currentTime;
function updateTime (){
Seconds = timeDif;
Hours = Math.floor(Seconds/3600);
Seconds -= Hours * 3600;
Minutes = Math.floor(Seconds/60);
Seconds -= Minutes * 60;
}
function tick (){
clearTimeout(timer);
updateTime();
displayTime();
if(timeDif > 0) {
timeDif - 1;
timer = setTimeout(tick, 1*1000)
}else {
$("#roundendtime").html("Timer done");
}
}
function displayTime() {
var out;
out = moment().hours(Hours).format('HH')+':'+moment().minutes(Minutes).format('mm')+':'+moment().seconds(Seconds).format('ss');
$("#roundendtime").html(out);
}
var timer = setTimeout(tick, 1*1000);
}
I am coding an online timed exam and for the timer to run I am using JS! The code for the timer to start and calculate the time and submit the exam when timer expires is as follows:
<script>
//Once the complete page is loaded the GIF image disappears and questions are displayed
function StartTimer()
{
document.getElementById('Loading').style.display = "none";
document.getElementById('Loaded').style.display = "block";
document.getElementById('1').style.display = "block";
document.getElementById('qustn1').style.backgroundColor="#dd6e23";
}
//Sets the Interval to the time
var ct = setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>);
function submitForm()
{
document.getElementById("submit").submit();
}
function calculate_time()
{
var end_time = "<?php echo $_SESSION["start_time"]; ?>"; // Get end time from session variable (total time in seconds).
var dt = new Date(); // Create date object.
var time_stamp = dt.getTime()/1000; // Get current minutes (converted to seconds).
var total_time = end_time - Math.round(time_stamp); // Subtract current seconds from total seconds to get seconds remaining.
var mins = Math.floor(total_time / 60); // Extract minutes from seconds remaining.
var secs = total_time - (mins * 60); // Extract remainder seconds if any.
if(secs < 10){secs = "0" + secs;} // Check if seconds are less than 10 and add a 0 in front.
document.getElementById("txt").value = mins + ":" + secs; // Display remaining minutes and seconds.
// Check for end of time, stop clock and display message.
if(mins <= 0)
{
if(secs <= 0 || mins < 0)
{
clearInterval(ct);
document.getElementById("txt").value = "0:00";
submitForm();
}
}
}
The above code runs well and even when the timer expires, the exam submits automatically. But, I am trying to call the setTimeOut() and setInterval() methods once the body is completely loaded i.e setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>); should be in the startTimer().
<body onload="StartTimer()">
......
<script>
.....
function StartTimer()
{
document.getElementById('Loading').style.display = "none";
document.getElementById('Loaded').style.display = "block";
document.getElementById('1').style.display = "block";
document.getElementById('qustn1').style.backgroundColor="#dd6e23";
var ct = setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>);
}
.....
</script>
But when I do this, I am unable to execute the code exactly. Even though timer reaches 0:00 the exam cannot be submitted, instead negative timer is running!! Please help me!!
The problem is incorrect scope for variable ct in the second code. Actually, you should put this variable in a context that is available for *calculate_time* function.
For example, you can try out this code which moves variable ct to the out-most scope:
<body onload="StartTimer()">
......
<script>
.....
var ct = null;
function StartTimer() {
document.getElementById('Loading').style.display = "none";
document.getElementById('Loaded').style.display = "block";
document.getElementById('1').style.display = "block";
document.getElementById('qustn1').style.backgroundColor="#dd6e23";
ct = setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>);
}
function submitForm() {
document.getElementById("submit").submit();
}
function calculate_time() {
var end_time = "<?php echo $_SESSION["start_time"]; ?>"; // Get end time from session variable (total time in seconds).
var dt = new Date(); // Create date object.
var time_stamp = dt.getTime()/1000; // Get current minutes (converted to seconds).
var total_time = end_time - Math.round(time_stamp); // Subtract current seconds from total seconds to get seconds remaining.
var mins = Math.floor(total_time / 60); // Extract minutes from seconds remaining.
var secs = total_time - (mins * 60); // Extract remainder seconds if any.
if(secs < 10){secs = "0" + secs;} // Check if seconds are less than 10 and add a 0 in front.
document.getElementById("txt").value = mins + ":" + secs; // Display remaining minutes and seconds.
// Check for end of time, stop clock and display message.
if(mins <= 0) {
if(secs <= 0 || mins < 0) {
clearInterval(ct);
document.getElementById("txt").value = "0:00";
submitForm();
}
}
}
.....
</script>
......
</body>
The best way to find the root of problems like this, is using a javascript debugger like FireBug that will easily pinpoint the root of your problem.
I worked on a Online Quiz app where I have to implement timer.
I created one Javascript function that I call on body load
`< script language ="javascript" >
var tim;
var min = '${sessionScope.min}';
var sec = '${sessionScope.sec}';
function customSubmit(someValue){
document.questionForm.minute.value = min;
document.questionForm.second.value = sec;
document.questionForm.submit();
}
function examTimer() {
if (parseInt(sec) >0) {
document.getElementById("showtime").innerHTML = "Time Remaining :"+min+" Minutes ," + sec+" Seconds";
sec = parseInt(sec) - 1;
tim = setTimeout("examTimer()", 1000);
}
else {
if (parseInt(min)==0 && parseInt(sec)==0){
document.getElementById("showtime").innerHTML = "Time Remaining :"+min+" Minutes ," + sec+" Seconds";
alert("Time Up");
document.questionForm.minute.value=0;
document.questionForm.second.value=0;
document.questionForm.submit();
}
if (parseInt(sec) == 0) {
document.getElementById("showtime").innerHTML = "Time Remaining :"+min+" Minutes ," + sec+" Seconds";
min = parseInt(min) - 1;
sec=59;
tim = setTimeout("examTimer()", 1000);
}
}
}
< /script>
`
Value of variable min and sec are set by sessionVariable which hold the exam time in session.
The complete application with Timer functionality is available here
http://www.edureka.co/blog/creating-an-online-quiz-application-implementing-countdown-timer/
I am trying to make a count down timer. I manage to make one but the problem with this is it stops when I close browser. So when user revisit my site it restart again. What I want is to keep that timer. For example, if user leaves my site at timer 22:14:09. So timer will continue. Lets say the user revisits my site after an hour so the time should be 21:14:09. How can I do that?
Here is my JS
$(function () {
var hrs, mins, secs, TimerRunning, TimerID,
Timer = {
init: function () {
hrs = 23;
mins = 59;
secs = 59;
TimerRunning = false;
Timer.StopTimer();
Timer.StartTimer();
},
StopTimer: function () {
if(TimerRunning)
clearTimeout(TimerID);
TimerRunning=false;
},
StartTimer: function () {
TimerRunning = true;
$('.timer').html(Timer.Pad(hrs) + ":" + Timer.Pad(mins) + ":" + Timer.Pad(secs));
TimerID = self.setInterval("StartTimer()", 1000);
if(hrs == 0 && mins == 0 && secs == 0)
StopTimer();
if (secs == 0) {
mins--;
secs = 59;
}
if (mins == 0) {
hrs--;
mins = 59;
}
secs--;
setTimeout(function () { Timer.StartTimer(); }, 1000);
},
Pad: function (number) {
if(number < 10)
number = 0+""+number;
return number;
}
};
Timer.init();
});
Update
DEMO
Here is my solution for this problem.
// use hours, minutes & seconds to set time limit
var hours = 1,
minutes = 30,
seconds = 0,
maxTime = ( ( hours * 3600 ) + ( minutes * 60 ) + seconds ) * 1000,
// if timeleft not in localStorage then default to maxTime
timeLeft = ( localStorage.timeLeft || maxTime ),
startTime = new Date(),
intervalRef;
// check if user has already used up time
if( timeLeft > 0 ) {
intervalRef = setInterval( setTimeLeft, 5000 );
} else {
stopTrackingTime();
}
function setTimeLeft( ) {
// if user has used up time exit
if( localStorage.timeLeft < 0 ) {
stopTrackingTime();
}
// calculate how long user has left
var elapsed = ( new Date() - startTime );
localStorage.timeLeft = timeLeft - elapsed;
};
// function called once user has used up time
function stopTrackingTime( ) {
clearInterval( intervalRef );
alert( "end of time allowed" );
}
Fiddle here
You could store the time in LocalStorage, and it would be persistent across browser restarts.
In your case something as simple as
localStorage["mytimer"] = JSON.stringify([hrs, mins, secs]);
should work for storage, and you could do
var previousTime = JSON.parse(localStorage["mytimer"]);
to retrieve the previous value.
You could read more about it here: http://diveintohtml5.info/storage.html.
You could modify your StartTimer function so that every time it is called a local time stamp (new Date) be saved in cookie or localStorage. Besides, the setTimeout isn't very reliable, your should adjust the time count with real time every now and then.