How to edit this function to make 3 things instead of 2 - javascript

I use this function with cache to make if the user enter the site for first time in last
x minutes redirect him and if this is the second time press the button i now want to add if this is the third time in last x minutes to do another thing.
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(";").shift();
}
function setLastAccess() {
const date = new Date();
const expireMs = 0.5 * 60 * 1000; // number of minutes
date.setTime(date.getTime() + expireMs);
document.cookie = `lastAccess=${new Date().getTime()};expires=${date.toUTCString()};path=/`;
}
if (!getCookie('lastAccess')) {
window.location.href = "http://google.com";
setLastAccess(); // set your last access at the end
} else {
setTimeout(function() {
document.getElementById('button-login').click();
}, 1000);
}

You can maintain a counter in localStorage whenever user access the site, and update it. Check for the count and if it is 3, run your logic.
You can also store it in cookie if it needs to be transferred to server.
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(";").shift();
}
function setLastAccess() {
const date = new Date();
const expireMs = 0.5 * 60 * 1000; // number of minutes
date.setTime(date.getTime() + expireMs);
document.cookie = `lastAccess=${new Date().getTime()};expires=${date.toUTCString()};path=/`;
}
function numAccess() {
if(!localStorage.getItem('accessCount')) {
localStorage.setItem('accessCount', '1');
} else {
localStorage.setItem(+localStorage.getItem('accessCount') + 1)
}
}
if (!getCookie('lastAccess')) {
window.location.href = "http://google.com";
setLastAccess(); // set your last access at the end
numAccess();
} else {
setTimeout(function() {
numAccess();
document.getElementById('button-login').click();
}, 1000);
}
if(+localStorage.getItem('accessCount') === 3) {
// Do some stuff
}

Related

Why does my Code is not reloading by the time Given in Text field

window.onload = function() {
onPageLoad();
}
var reftime;
function refreshPage(){
var refreshtime = document.getElementById("r_time").value;
//var reftime;
reftime = setInterval(function() {
window.location.reload(true);
}, refreshtime*60000);
}
Above code is Js for reloading page.
<input id='r_time' type='text' name='r_time' value= ''/>
<input id='r_btn' type='button' value='Apply' style="font-size:12px;font-family:Helvetica;" onclick='refreshPage();'/>
This is my code it for reload my page it is reloading once when i gave time interval in minutes.But after once reloaded it is not reloading again.
The problem is that after reloading the window with window.location.reload(true) all your javascipt variables and intervals are gone.
So as soon as you reloaded the page for the first time no interval is running that will reload the page another time.
To get around this issue you have a few possibilities:
Don't reload the whole page. Just reload part of the page that changes.
This could be done with an asynchronous AJAX call retrieving the content to display from a server
Check out this solution to learn how to keep variables after reloading a html page.
After the reload you can then check in the window.onload function if you should start another inverval after some specified time.
For exaple if you want your page to reload itself after 1 minute, You can try just writing location.reload(0) in your onPageLoad() function like this:
window.onload = function() {
setTimeout(onPageLoad, 60000);
}
function onPageLoad() {
location.reload(0);
}
That should make your page reload after 1 minute(example).
Upon refresh, you'll start over again and the values of variables set will be gone. You can save the value using localStorage. Also, using setInterval in this case is unnecessary, you must use setTimeout
var reftime;
var input = document.getElementById("r_time");
window.onload = function() {
reftime = localStorage.getItem('time');
if (reftime) {
input.value = reftime;
refreshPage();
}
}
function refreshPage(){
var time = input.value || reftime;
localStorage.setItem('time', time);
setTimeout(function() {
window.location.reload(true);
}, time);
}
window.onload = function () {
onPageLoad();
}
var reftime;
function refreshPage() {
var refreshtime = document.getElementById("r_time").value;
// var reftime;
reftime = setInterval(function () {
location.reload(true);
}, refreshtime * 60000);
}
See if that Works.
For this code I am using cookies to save the value every time the website refreshes.
const _ = {
cookie_class: class cookies {
constructor() {
}
setCookie(cookie_name, cookie_value, expire_in_days) {
var d = new Date();
d.setTime(d.getTime() + (expire_in_days * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cookie_name + "=" + cookie_value + ";" + expires + ";path=/";
}
getCookie(cookie_name) {
var name = cookie_name + "=";
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 "";
}
exists(cookie) {
var user = this.getCookie(cookie);
if (user != "") {
return true;
} else {
return false;
}
}
}
}
const cookies = new _.cookie_class();
let interval;
const refresh = () => {
location.reload();
}
let cookie_name = "refresh_interval";
window.onload = () => {
if (cookies.exists(cookie_name)) {
interval = setInterval(refresh, parseInt(cookies.getCookie(cookie_name)));
}
}
const update = () => {
let value = document.getElementById('input').value;
if (!isNaN(parseInt(value))) {
cookies.setCookie(cookie_name, parseInt(value), 365);
clearInterval(interval);
interval = setInterval(refresh, parseInt(value));
} else {
// Handle is however you would Like:
// The input is not a Number
}
};
// Listeners
document.getElementById('apply-btn').addEventListener('click', (event) => {
event.preventDefault();
update();
});
Tell me if it works for you!

How to keep running my Countdown after a refresh?

I'm learning JS and I'm stuck...
I want to create a countdown (it's done, my countdown is working) who keep running when the page is reloaded.
I used the sessionStorage to "save" the countdown value and also to check if a sessionStorage exists when the page is loaded.
The problem is, I don't know how keep running the countdown with values saved in the sessionStorage.
Could you please help me?
class Timer {
constructor(secondes, minutes) {
this.secondes = secondes;
this.minutes = minutes;
this.button = document.getElementById("button");
this.counter = document.getElementById("counter");
this.storageCheck();
}
countdown(minutes) {
var seconds = this.secondes;
var mins = this.minutes;
var myCounter = this.counter;
function tick() {
var current_minutes = mins-1;
seconds--;
myCounter.innerHTML = current_minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
var duration = sessionStorage.setItem("timer", myCounter.innerHTML);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
countdown(mins-1);
}
}
}
tick();
}
buttonClick() {
button.addEventListener("click", () => {
this.countdown(this.minutes);
})
}
storageCheck() {
if (sessionStorage.getItem("timer")) {
// keep the countdown running
}
}
}
let newTimer = new Timer(60, 20);
newTimer.buttonClick();
<!DOCTYPE html>
<html>
<head>
<title>Test Countdown</title>
</head>
<body>
<div id="counter"></div>
<button id="button">Run</button>
<script type="text/javascript" src="countdown.js"></script>
</body>
</html>
In constructor before initializing secondes and minutes check if they are in the storage.If they dont exists then only set the this.secondes = secondes and this.minutes = minutes;
constructor(secondes, minutes) {
this.button = document.getElementById("button");
this.counter = document.getElementById("counter");
if(!this.storageCheck()){ //check if seconds are mins are stored in storage
this.secondes = secondes; //if not set mins and sec to value passed in constructor
this.minutes = minutes;
}
else{
this.countdown(this.minutes);
}
}
In storage check function , check if the values are there, if there get the values and set to this.secondes and this.minutes and return true else return false
storageCheck() {
//if both mins and secs exists
if (sessionStorage.getItem("mins") &&sessionStorage.getItem("secs")) {
// keep the countdown running
this.minutes=parseInt(sessionStorage.getItem("mins"));//get min
this.secondes=parseInt(sessionStorage.getItem("secs"));//get secs
return true;
}
else
return false;
}
and in countdown funciton save the values to storage
sessionStorage.setItem("mins",vm.minutes);//set current min
sessionStorage.setItem("secs",vm.secondes);//set current sec
Try running this here :https://jsbin.com/bavexigute/1/edit?html,js,console,output
class Timer {
constructor(secondes, minutes) {
this.button = document.getElementById("button");
this.counter = document.getElementById("counter");
if(!this.storageCheck()){ //check if seconds are mins are stored in storage
this.secondes = secondes; //if not set mins and sec to value passed in constructor
this.minutes = minutes;
}
else{
this.countdown();
}
}
countdown() {
debugger;
var vm=this;
if(!(this.minutes-1<0))
this.minutes--;
let tick= function(){
vm.secondes--
if(vm.secondes==0){
vm.secondes=59;
vm.minutes--;
}
vm.counter.innerHTML = vm.minutes + ":" + (vm.secondes < 10 ? "0" : "") + vm.secondes;
if(vm.minutes == 0 && vm.secondes-1==0){
vm.secondes--;
vm.counter.innerHTML = vm.minutes + ":" + vm.secondes-1;
}
else{
setTimeout(tick,1000);
}
sessionStorage.setItem("mins",vm.minutes);//set current min
sessionStorage.setItem("secs", vm.secondes);//set current sec
}
setTimeout(tick,1000);
}
buttonClick() {
button.addEventListener("click", () => {
this.countdown();
})
}
storageCheck() {
//if both mins and secs exists
if (sessionStorage.getItem("mins") && sessionStorage.getItem("secs")) {
// keep the countdown running
this.minutes=parseInt(sessionStorage.getItem("mins"));//get min
this.secondes=parseInt(sessionStorage.getItem("secs"));//get secs
return true;
}
else
return false;
}
}
let newTimer = new Timer(60, 20);
newTimer.buttonClick();
You could use your storage check function to override the minutes and seconds arguments if it exists.
constructor(mins, secs) {
this.mins = mins
this.secs = secs
this.checkStorage = this.checkStorage.bind(this)
this.checkStorage(mins, secs)
}
checkStorage(mins, secs) {
if(window.storage) { // or whatever
this.secs = window.storage.secs
this.mins = window.storage.mins
}
}
Something along those lines. Basically just have the setStorage function change the values that have been set in the constructor.
You can do a simple trick by doing this
window.onload = function() {
let minutes = sessionStorage.getItem("minutes")
let seconds = sessionStorage.getItem("seconds")
let newTimer = new Timer(seconds, minutes);
};
And in sessionStorage instead of storing the whole innerHtml store minutes and seconds hopefully it will solve your problem

timer on sessionStorage stop on refresh

I am doing a timer that I store in a sessionStorage but if a refresh the page the timer stop! some help please
function time (secondes) {
const temps = Date.now();
const apres = temps + secondes * 1000;
const timer = setInterval(() => {
const secondsLeft = Math.round((apres - Date.now()) / 1000)
if (secondsLeft < 0) {
clearInterval(timer);
sessionStorage.clear();
if (sessionStorage.getItem('Timer') === null) {
$(".reservation").css("display", "none");
}
return;
}
sessionStorage.setItem("Timer", secondsLeft)
}, 1000);
}
the getItem("timer") here is just to check if the timer is over, I am using this Timer item in another method
thx
SessionStorage persist even if the page reloads. Read this:https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
What you should do is, after you refresh the page, get the value of Timer again from SessionStorage and then again call the method.
function time (secondes) {
const temps = Date.now();
const apres = temps + secondes * 1000;
const timer = setInterval(() => {
const secondsLeft = Math.round((apres - Date.now()) / 1000)
if (secondsLeft <= 0) {
clearInterval(timer);
sessionStorage.clear();
//you dont need below if condition as secondsLeft is already 0. Commented if condition.
//if (sessionStorage.getItem('Timer') === null) {
$(".reservation").css("display", "none");
//}
return;
}
else{
//update the div content and show the current timer value in the div or in the span inside the div. (write a separate function for this).
}
sessionStorage.setItem("Timer", secondsLeft)
}, 1000);
}
//Method to call after page load:
function startTimerOnPageLoad(){
var x = parseInt( sessionStorage.getItem('Timer'));
//put a check, Timer is present in sessionStorage and x is not undefined. I've not added it here purposely.
time(x);
}

How to clear JS timers

I've got a user which i get from database. For each user is possible to reset his password. But it's possible only one time for three minutes. If password was reseted less than three minutes, I show timer with JS, which show how much time left for next reset and reset button is disabled. When countdown is finished, button become availiable and displayed inscription "Password reset avaliable". Because the each user has his own timer, when I select another user, previous timer must be stopped with reset() function, and must be started other timer. It's just the only one timer must be in one time.
Timer:
var timerCount = 0;
function startTimer(minute, second) {
timerCount++;
start(minute, second);
}
function start(minute, second) {
disableButton('resetPasswordButton');
var m = minute;
var s = second;
if (timerCount == 0) {
document.getElementById('expiredTimeOutputText').innerHTML = "Password reset avaliable";
m = 0;
s = 0;
enableButton('resetPasswordButton');
return ;
}
if (s == 0) {
if (m == 0) {
reset();
document.getElementById('expiredTimeOutputText').innerHTML = "Password reset avaliable!";
enableButton('resetPasswordButton');
return ;
}
m--;
s = 59;
} else
s--;
document.getElementById('expiredTimeOutputText').innerHTML = m + ":" + s;
setTimeout(function () {
start(m, s);
}, 1000);
}
function reset() {
if (timerCount > 0) {
timerCount = 0;
}
}
function enableButton(id){
document.getElementById(id).disabled = false;
}
function disableButton(id){
document.getElementById(id).disabled = true;
}
method to start timer on button click
public void changePassword() {
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("startTimer(\"0\", \"40\")");
Date tmpDate = new Date();
Long diff = tmpDate.getTime();
mainDataBean.setResetTimer(applicantsTableSelectedRow.get("ID"), diff.toString());
}
method to start timer on user change
public void checkTimerForNewUser() {
RequestContext requestContext = RequestContext.getCurrentInstance();
Date tmpDate = new Date();
Long currentTime = tmpDate.getTime();
requestContext.execute("reset()");
if (applicantsTableSelectedRow != null) {
if (!mainDataBean.getResetTimer(applicantsTableSelectedRow.get("ID")).equals("noTimer")) {
Long applicantTimerTime = Long.parseLong(mainDataBean.getResetTimer(applicantsTableSelectedRow.get("ID")));
if (currentTime - applicantTimerTime > timerValue) {
mainDataBean.deleteResetTimer(applicantsTableSelectedRow.get("ID"));
}
else {
expiredTimeMinute = (timerValue - (currentTime - applicantTimerTime)) / 60000;
expiredTimeSecond = (timerValue - (currentTime - applicantTimerTime)) / 1000 - expiredTimeMinute * 60;
requestContext.execute("startTimer(\"" + expiredTimeMinute + "\", \"" + expiredTimeSecond + "\")");
}
}
}
}
If consistently reset user password, one after another, everything works fine. But if I consistently reset password for 5 users, and after that I return to first user with reseted password, if time isn't expired, I've got all 5 timers, which overlap one another, display 5 different times 5 time in second. But in theory they must stop because of reset function. How does it possible to make the only one timer exist? Do I stop functions wrong?
Example with clearTimeout:
function start(minute, second) {
disableButton('resetPasswordButton');
var m = minute;
var s = second;
if (timerCount == 0) {
document.getElementById('expiredTimeOutputText').innerHTML = "Reset Button Available!";
clearTimeout(timeout);
enableButton('resetPasswordButton');
return ;
}
if (s == 0) {
if (m == 0) {
reset();
clearTimeout(timeout);
document.getElementById('expiredTimeOutputText').innerHTML = "Reset Button Available!";
enableButton('resetPasswordButton');
return ;
}
m--;
s = 59;
} else
s--;
document.getElementById('expiredTimeOutputText').innerHTML = m + ":" + s;
timeout = setTimeout(function () {
start(m, s);
}, 1000);
}
You can clear timers with:
clearTimeout for setTimeout
clearInterval for setInterval
Example:
// will *never* run since we clear it below, immediately after we
// create it.
var timeout = setTimeout(() => {
console.log('foo')
}, 1000)
clearTimeout(timeout)
// will run only *once* since we clear it when it's called
var interval = setInterval(() => {
console.log('bar')
clearInterval(interval)
}, 1000)

multiple stopwatch in jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to make multiples stopwatches in jquery, but the problem is i want the stopwatch the respective stopwatch to sun when we hit the corresponding button, and should stop when we hit button for another stopwatch and that respective stopwatch should start simultaneously, please see the image for reference, i know the question is not so clear, sorry for inconvenience.
thanks in advance.
try this one:
$(document).ready(function() {
(function($){
$.extend({
APP : {
formatTimer : function(a) {
if (a < 10) {
a = '0' + a;
}
return a;
},
startTimer : function(dir) {
var a;
// save type
$.APP.dir = dir;
// get current date
$.APP.d1 = new Date();
switch($.APP.state) {
case 'pause' :
// resume timer
// get current timestamp (for calculations) and
// substract time difference between pause and now
$.APP.t1 = $.APP.d1.getTime() - $.APP.td;
break;
default :
// get current timestamp (for calculations)
$.APP.t1 = $.APP.d1.getTime();
// if countdown add ms based on seconds in textfield
if ($.APP.dir === 'cd') {
$.APP.t1 += parseInt($('#cd_seconds').val())*1000;
}
break;
}
// reset state
$.APP.state = 'alive';
$('#' + $.APP.dir + '_status').html('Running');
// start loop
$.APP.loopTimer();
},
pauseTimer : function() {
// save timestamp of pause
$.APP.dp = new Date();
$.APP.tp = $.APP.dp.getTime();
// save elapsed time (until pause)
$.APP.td = $.APP.tp - $.APP.t1;
// change button value
$('#' + $.APP.dir + '_start').val('Resume');
// set state
$.APP.state = 'pause';
$('#' + $.APP.dir + '_status').html('Paused');
},
stopTimer : function() {
// change button value
$('#' + $.APP.dir + '_start').val('Restart');
// set state
$.APP.state = 'stop';
$('#' + $.APP.dir + '_status').html('Stopped');
},
resetTimer : function() {
// reset display
$('#' + $.APP.dir + '_ms,#' + $.APP.dir + '_s,#' + $.APP.dir + '_m,#' + $.APP.dir + '_h').html('00');
// change button value
$('#' + $.APP.dir + '_start').val('Start');
// set state
$.APP.state = 'reset';
$('#' + $.APP.dir + '_status').html('Reset & Idle again');
},
endTimer : function(callback) {
// change button value
$('#' + $.APP.dir + '_start').val('Restart');
// set state
$.APP.state = 'end';
// invoke callback
if (typeof callback === 'function') {
callback();
}
},
loopTimer : function() {
var td;
var d2,t2;
var ms = 0;
var s = 0;
var m = 0;
var h = 0;
if ($.APP.state === 'alive') {
// get current date and convert it into
// timestamp for calculations
d2 = new Date();
t2 = d2.getTime();
// calculate time difference between
// initial and current timestamp
if ($.APP.dir === 'sw') {
td = t2 - $.APP.t1;
// reversed if countdown
} else {
td = $.APP.t1 - t2;
if (td <= 0) {
// if time difference is 0 end countdown
$.APP.endTimer(function(){
$.APP.resetTimer();
$('#' + $.APP.dir + '_status').html('Ended & Reset');
});
}
}
// calculate milliseconds
ms = td%1000;
if (ms < 1) {
ms = 0;
} else {
// calculate seconds
s = (td-ms)/1000;
if (s < 1) {
s = 0;
} else {
// calculate minutes
var m = (s-(s%60))/60;
if (m < 1) {
m = 0;
} else {
// calculate hours
var h = (m-(m%60))/60;
if (h < 1) {
h = 0;
}
}
}
}
// substract elapsed minutes & hours
ms = Math.round(ms/100);
s = s-(m*60);
m = m-(h*60);
// update display
$('#' + $.APP.dir + '_ms').html($.APP.formatTimer(ms));
$('#' + $.APP.dir + '_s').html($.APP.formatTimer(s));
$('#' + $.APP.dir + '_m').html($.APP.formatTimer(m));
$('#' + $.APP.dir + '_h').html($.APP.formatTimer(h));
// loop
$.APP.t = setTimeout($.APP.loopTimer,1);
} else {
// kill loop
clearTimeout($.APP.t);
return true;
}
}
}
});
$('#sw_start').live('click', function() {
$.APP.startTimer('sw');
});
$('#cd_start').live('click', function() {
$.APP.startTimer('cd');
});
$('#sw_stop,#cd_stop').live('click', function() {
$.APP.stopTimer();
});
$('#sw_reset,#cd_reset').live('click', function() {
$.APP.resetTimer();
});
$('#sw_pause,#cd_pause').live('click', function() {
$.APP.pauseTimer();
});
})(jQuery);
});
DEMO HERE
OR
$(function () {
// Never assume one widget is just used once in the page. You might
// think of adding a second one. So, we adjust accordingly.
$('.stopwatch').each(function () {
// Cache very important elements, especially the ones used always
var element = $(this);
var running = element.data('autostart');
var hoursElement = element.find('.hours');
var minutesElement = element.find('.minutes');
var secondsElement = element.find('.seconds');
var millisecondsElement = element.find('.milliseconds');
var toggleElement = element.find('.toggle');
var resetElement = element.find('.reset');
var pauseText = toggleElement.data('pausetext');
var resumeText = toggleElement.data('resumetext');
var startText = toggleElement.text();
// And it's better to keep the state of time in variables
// than parsing them from the html.
var hours, minutes, seconds, milliseconds, timer;
function prependZero(time, length) {
// Quick way to turn number to string is to prepend it with a string
// Also, a quick way to turn floats to integers is to complement with 0
time = '' + (time | 0);
// And strings have length too. Prepend 0 until right.
while (time.length < length) time = '0' + time;
return time;
}
function setStopwatch(hours, minutes, seconds, milliseconds) {
// Using text(). html() will construct HTML when it finds one, overhead.
hoursElement.text(prependZero(hours, 2));
minutesElement.text(prependZero(minutes, 2));
secondsElement.text(prependZero(seconds, 2));
millisecondsElement.text(prependZero(milliseconds, 3));
}
// Update time in stopwatch periodically - every 25ms
function runTimer() {
// Using ES5 Date.now() to get current timestamp
var startTime = Date.now();
var prevHours = hours;
var prevMinutes = minutes;
var prevSeconds = seconds;
var prevMilliseconds = milliseconds;
timer = setInterval(function () {
var timeElapsed = Date.now() - startTime;
hours = (timeElapsed / 3600000) + prevHours;
minutes = ((timeElapsed / 60000) + prevMinutes) % 60;
seconds = ((timeElapsed / 1000) + prevSeconds) % 60;
milliseconds = (timeElapsed + prevMilliseconds) % 1000;
setStopwatch(hours, minutes, seconds, milliseconds);
}, 25);
}
// Split out timer functions into functions.
// Easier to read and write down responsibilities
function run() {
running = true;
runTimer();
toggleElement.text(pauseText);
}
function pause() {
running = false;
clearTimeout(timer);
toggleElement.text(resumeText);
}
function reset() {
running = false;
pause();
hours = minutes = seconds = milliseconds = 0;
setStopwatch(hours, minutes, seconds, milliseconds);
toggleElement.text(startText);
}
// And button handlers merely call out the responsibilities
toggleElement.on('click', function () {
(running) ? pause() : run();
});
resetElement.on('click', function () {
reset();
});
// Another advantageous thing about factoring out functions is that
// They are reusable, callable elsewhere.
reset();
if(running) run();
});
});
DEMO HERE

Categories

Resources