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
Related
Summary of my program:
The user speaks to the computer for 8 minutes (there is a countdown function too) - a button is clicked to initiate speech recognition and the countdown timer
When 8 minutes is reached, speech recognition stops
There is a 10 second delay/pause and then speech recognition continues again (without the user needing to initiate speech recognition by themselves) and the user speaks to the computer for another 2 minutes (once minutes and seconds == 0, speech recognition stops again).
My code:
//HTML STUFF
<html>
<button id="speak_button">Click</button> //button that when clicked triggers speech recognition
<div id="circle"><p id="countdown">8:00</p></div> // circle showing countdown from 8 minutes
</html>
//SPEECH RECOGNITION STUFF
<script>
let isListening = false;
window.addEventListener('DOMContentLoaded', function() {
document.getElementById("speak_button").addEventListener('click', function() {
if (isListening) {
console.log('STOPPING RECOGNITION');
isListening = false;
recognition.stop();
} else {
console.log('STARTING RECOGNITION');
recognition.start();
setInterval(updateCountDown,1000); //So the updateCountDown function occurs 1 second after clicking
updateCountDown();
isListening = true;
}
});
});
//COUNTDOWN FUNCTION
const startingMinutes = 8;
let time = startingMinutes * 60;
function updateCountDown() {
document.getElementById("countdown").innerHTML = "8:00";
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 8 ? '0' + seconds : seconds;
document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (minutes == 0 && seconds == 0) {
recognition.abort();
isListening = false;
}
};
<script>
Once the countdown timer reaches 0 (once the 8 minutes is complete), I want there to be a 10 second pause for the user and then they have a further 2 minutes of speaking! I tried using a setTimeout function both inside and outside the if statement below but that doesn't seem to work!
function updateCountDown() {
document.getElementById("countdown").innerHTML = "8:00";
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 8 ? '0' + seconds : seconds;
document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (minutes == 0 && seconds == 0) {
recognition.abort();
isListening = false;
setTimeout(updateCountDownNew, 10,000); //SET TIMEOUT FUNCTION TRIAL
//updateCountDownNew is the same function as updateCountDown but runs for 2 minutes!
}
};
//updateCountDownNew function is below
function updateCountDownNew() {
const startingMinutes = 2;
let time = startingMinutes * 60;
isListening = true;
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 2 ? '0' + seconds : seconds;
document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (minutes == 0 && seconds == 0) {
recognition.abort();
isListening = false;
}
};
If anyone has any advice that would be great!
I want to make 3 countdown timers where the next one starts when the last one ends (the first timer will start counting down the time automatically, but the second timer will only start when the first one reaches 0:00 and the third one will only start when the second one reaches 0:00).
I found this code for a countdown timer:
function countDown() {
var seconds = 60;
var mins = 5;
function clickClock() {
var counter = document.getElementById("countdown1");
var currentMinutes = mins - 1;
seconds--;
counter.innerHTML = currentMinutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if(seconds > 0) {
setTimeout(clickClock, 1000);
} else {
if(mins > 1) {
countDown(mins-1);
}
}
}
clickClock();
}
countDown();
On my HTML, I have 3 spans, each with a unique ID (#countdown1, #countdown2, #countdown3)
I have tried passing in an parameter to the clickClock() function called counter so that whenever I called the function I could enter the id of the element I wanted to affect, didn't work.
I could just make 2 other functions that would do exactly the same thing but would change the counter variable, but I'd like to avoid repeating unnecessary things in my code.
How could this be done?
Any help is appreciated :)
I'd do something like this:
/////////// USAGE
const timersDurationInMilliseconds = 1000 * 5; // for 5 minutes do: 1000 * 60 * 5
// Render initial timer content
RenderTimer('countdown1', timersDurationInMilliseconds);
RenderTimer('countdown2', timersDurationInMilliseconds);
RenderTimer('countdown3', timersDurationInMilliseconds);
// Start countdown, then start another ones
countDown(timersDurationInMilliseconds, 'countdown1')
.then(() => countDown(timersDurationInMilliseconds, 'countdown2'))
.then(() => countDown(timersDurationInMilliseconds, 'countdown3'))
.then(() => alert('All timers finished!'));
/////////// REQUIRED METHODS
function countDown(durationInMilliseconds, elementId) {
return new Promise((resolve, reject) => {
const updateFrequencyInMilliseconds = 10;
const currentTimeInMilliseconds = new Date().getTime();
const endTime = new Date(currentTimeInMilliseconds + durationInMilliseconds);
function updateTimer(elementId) {
let timeLeft = endTime - new Date();
if (timeLeft > 0) {
// We're not done yet!
setTimeout(updateTimer, updateFrequencyInMilliseconds, elementId);
} else {
// Timer has finished!
resolve();
// depending on update frequency, timer may lag behind and stop few milliseconds too late
// this will cause timeLeft to be less than 0
// let's reset it back to 0, so it renders nicely on the page
timeLeft = 0;
}
RenderTimer(elementId, timeLeft);
}
updateTimer(elementId);
});
}
function padNumber(number, length) {
return new String(number).padStart(length || 2, '0'); // adds leading zero when needed
}
function RenderTimer(elementId, timeLeft) {
const hoursLeft = Math.floor(timeLeft / 1000 / 60 / 60 % 60);
const minutesLeft = Math.floor(timeLeft / 1000 / 60 % 60);
const secondsLeft = Math.floor(timeLeft / 1000 % 60);
const millisecondsLeft = timeLeft % 1000;
const counterElement = document.getElementById(elementId);
counterElement.innerHTML = `${padNumber(hoursLeft)}:${padNumber(minutesLeft)}:${padNumber(secondsLeft)}.${padNumber(millisecondsLeft, 3)}`;
}
<p>First countdown: <span id="countdown1"></span></p>
<p>Second countdown: <span id="countdown2"></span></p>
<p>Third countdown: <span id="countdown3"></span></p>
If you want to only display minutes and seconds, you can adjust that behavior in RenderTimer method.
If you don't plan on displaying milliseconds to the user, you may want to change how frequent the timer is updated and rendered on the page by adjusting the updateFrequencyInMilliseconds variable (e.g. from 10ms to 1000ms).
So i am writing a simple javascript timer, and at 30 seconds it prompts the user with an alert box if they would like to reset the count down or let it continue.
I am able to reset the timer however I get stuck when the user clicks cancel on the alert box.
I tried letting the timer just resume at its current time but that doesn't help as the alert box just keeps reappearing
I am still very new to javascript so I would like to stay using vanilla js till I get a deeper understanding of the fundamentals!
Any guidance would be greatly appreciated!
Heres my 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 + ":" + seconds;
if(timer<30){
var message = confirm("Would you like to extend timer?");
if (message == true) {
timer = 60 * 1;
}
else{
timer = timer;
}
}
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function resetTimer() {
timer = 60 * 1;
}
window.onload = function () {
var fiveMinutes = 60 * 1,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
just put if(timer==30) instead of if(timer<30) so that exactly at count of 30 units of time, you get asked once for confirmation at that instance (However be aware that until the confirmation is done, prompts will keep popping up every second). if you extend it, it will again wait till your timer goes down to 30 unit, else it will simply go down to 0 and break out.
function startTimer(duration, display) {
var timer = duration,
minutes,
seconds;
function timerFunc() {
timer -= 1;
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 == 30) {
var message = confirm("Would you like to extend timer?");
if (message == true) {
timer = 60;
} else return alert("Your timer has been stopped.")
}
setTimeout(timerFunc, 1000);
}
timerFunc();
}
I want to create a simple countdown timer in javascript or jquery.
I had implemented it using JS but what issue I am facing is if user refreshes the page then timer gets the refresh.
What I want is timer should not get the refresh.
Say timer is 5 min and if user refresh pages after 1 min the timer should continue to start from 4 min instead of 5 mins.
Here is code snippiet.
Its refresh the timer on page refresh.
var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
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 > 0 ) {
timeoutHandle=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();
}
countdown(2);
<div id="timer">2:00</div>
You just update the sessionStorage along with your counter and read it on starting the counter. Unfortunately the related snippet does not work on stackoverflow due to crossdomain policies - so here on codepen https://codepen.io/anon/pen/opNpVe
function countdown(seconds) {
seconds = parseInt(sessionStorage.getItem("seconds"))||seconds;
function tick() {
seconds--;
sessionStorage.setItem("seconds", seconds)
var counter = document.getElementById("timer");
var current_minutes = parseInt(seconds/60);
var current_seconds = seconds % 60;
counter.innerHTML = current_minutes + ":" + (current_seconds < 10 ? "0" : "") + current_seconds;
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
tick();
}
countdown(120);
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.