Remember if button was clicked + Stop interval doesnt work - javascript

so I'm trying to create two buttons. One is refreshing site on interval and second one should stop it after pressing, but the stop button isn't working. Second thing is that if I press start button it's not saved in local storage as I want it. Could you guys help me with this?
window.onload = function () {
if (localStorage.getItem("refresh")) {
startref()
}
};
function startref() {
let intervalId = setInterval(function () {
chrome.tabs.query({ active: true, currentWindow: true }, function (arrayOfTabs) {
var code = 'window.location.reload();';
chrome.tabs.executeScript(arrayOfTabs[0].id, { code: code });
});
}, 1000);
localStorage.setItem('refresh');
}
function stop() {
clearInterval(intervalId);
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("startbtn").addEventListener('click', startref);
});
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("stopbtn").addEventListener('click', stop);
});

localStorage.setItem function takes two arguments. One is key and another is the value for the key.
change this line
localStorage.setItem('refresh');
into this
localStorage.setItem('refresh',intervalId);
When you clear the interval first get the intervalId stored in the localStorage and then call clearInterval.
function stop() {
const intervalId = localStorage.getItem("refresh");
clearInterval(intervalId);
}

Related

How to make .one () method to work again without reloading the page

I have a chat application and I made that when the user writes in the TEXTAREA field to add a text under his name for example Typing ... but for personal reasons I would like this "Typing ..." to appear only once without repeating for each character.
I tried with the one () function but it works again only if user reloads the page.
$("textarea").one('input', function () {
HERE IS MY CODE TO ADD "TYPING.." UNDER HIS NAME
});
function sendMessage() {
HERE IS MY CODE TO DELETE "TYPING..." FROM UNDER HIS NAME
}
How can I make it work?
You could use a kind of throttling, using the following setTimeout-based, function:
// Returns a function that will call its callback argument
// only when a certain delay has passed. Another callback
// can be called to notify that the delay has expired
function throttle(f, milliseconds, ready = () => null) {
let timer = -1;
return function () {
if (timer === -1) f();
clearTimeout(timer);
timer = setTimeout(function () {
timer = -1;
ready();
}, milliseconds);
}
}
function sendMessage(msg) {
$("div").text("typing...");
}
function clearMessage() {
$("div").text("");
}
$("textarea").on('input', throttle(sendMessage, 3000, clearMessage));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea></textarea>
<div></div>
The "typing..." message will clear when during 3 seconds there was no typing. If typing starts again, then the message will be sent/displayed again. The message will not be sent again before it has been cleared.
You could work with a timeout, that will revert the typing state after a certain time. Clear the timeout while the user keeps typing.
const textArea = document.querySelector('.area')
const indicator = document.querySelector('.indicator')
let timeout = null
textArea.addEventListener('input', function() {
clearTimeout(timeout)
indicator.innerText = 'Typing...'
timeout = setTimeout(function() {
indicator.innerText = ''
}, 300)
})
.area,
.indicator {
display: block;
margin: 1rem;
}
<textarea class="area"></textarea>
<span class="indicator"></span>

Retrieve localStorage data in "start/stop" timer

I'm trying to retrieve localStorage data in a Start/Stop timer. My goal is to have the timer start automatically on page load but when the user leaves and comes back at a later date (page refresh), the timer will resume where it left off.
I'm close to getting this to work..but after each page refresh it starts back to 00:00:00.
I created a setTimeout function w/ a 3 second delay to illustrate that some of this is working.
Many thanks to anyone that can help put me on the right track.
Codepen
HTML
<!-- Timer -->
<div class="time-wrapper">
<strong>Time</strong>
<span id="time-total">00:00:00</span>
</div>
<!-- Controls -->
<div class="button-wrapper">
<button id="start-timer" class="button">Start</button>
<button id="pause-timer" class="button">Pause</button>
</div>
JS (with EasyTimer.js plugin)
/* Create Timer
********************************/
var timer = new Timer();
var timeTotal = $('#time-total'),
timeKey = 'time_stored',
timeStored = localStorage.getItem(timeKey);
// Update Event
timer.addEventListener('secondsUpdated', function (e) {
$(timeTotal).html(timer.getTimeValues().toString());
});
// Started Event
timer.addEventListener('started', function (e) {
$(timeTotal).html(timer.getTimeValues().toString());
});
// Start Timer
$('#start-timer').click(function () { timer.start(); });
$('#pause-timer').click(function () { timer.pause(); });
/* When page loads
********************************/
$(document).ready(function() {
setInterval(function() {
localStorage.setItem(timeKey, timeTotal.text());
}, 500);
if (timeStored) {
timeTotal.text(timeStored);
}
setTimeout(function() {
$('#start-timer').click();
timer.start();
}, 3000);
});
You can set the default value when you start the timer - see my example below. You might want to adjust the functionality of Start button accordingly, as it also calls the start() method of the timer. Please note i used different key for your localStorage (just in case you already have a set value in your browser) and i store only seconds which gets incremented everytime the event secondsUpdated is fired. There is no need for your own setInterval, as you can use the interval of the timer fired with the above mentioned event.
var timer = new Timer();
var timeTotal = $('#time-total'),
timeKey = 'time_stored_seconds',
timeStored = localStorage.getItem(timeKey);
// Update Event
timer.addEventListener('secondsUpdated', function (e) {
var newValue = parseInt(localStorage.getItem(timeKey) | 0)+1
localStorage.setItem(timeKey, newValue);
$(timeTotal).html(timer.getTimeValues().toString());
});
// Started Event
timer.addEventListener('started', function (e) {
$(timeTotal).html(timer.getTimeValues().toString());
});
// Start Timer
$('#start-timer').click(function () { timer.start(); });
$('#pause-timer').click(function () { timer.pause(); });
/* When page loads
********************************/
$(document).ready(function() {
if (timeStored) {
timeTotal.text(timeStored);
}else{
localStorage.setItem(timeKey, 0);
timeStored = 0
}
timer.start({ precision: 'seconds', startValues: {seconds: parseInt(timeStored)}});
});

clearInterval not working as I expect it too

I made a demo which is here. All you have to do is start typing in the text field, make sure you have the console open. So as you type, you'll instantly see the OMG Saved, and the counter in the console will go nuts.
Now click the button, watching the console you should see something like 11 or some other value, but you'll also see the counter reset and continues going. I do not want this. I want the counter to stop, I have clicked a button and while the page hasn't refreshed, the counter should stop if I understand these docs on setInterval().
the app I am developing which uses code very similar to this, does not refresh as most single page apps don't. So it is imperative that I have control over this setInterval.
So my question is:
How do I reset the counter such that, until I type again in the input box OR if the input box element cannot be found the flash message does not show up, the interval is set back to 0.
update
The following is the JavaScript code, which is run on the link provided above.
var ObjectClass = {
initialize: function() {
$('#flash-message').hide();
},
syncSave: function() {
$('#content').keypress(function(){
SomeOtherClass.autoSave = setInterval( function(){
$('#flash-message').show();
$('#flash-message').delay(1000).fadeOut('slow');
}, 500);
});
},
listenForClick: function() {
$('#click-me').click(function() {
console.log(SomeOtherClass.autoSave);
clearInterval(SomeOtherClass.autoSave);
});
}
};
var SomeOtherClass = {
autoSave: null
};
ObjectClass.initialize();
ObjectClass.syncSave();
ObjectClass.listenForClick();
You have to put this
clearInterval(SomeOtherClass.autoSave);
before this line:
SomeOtherClass.autoSave = setInterval( function(){
So that you kill the previous interval and you ahve ONLY ONE interval at the same time
Your code will be:
var ObjectClass = {
initialize: function () {
$('#flash-message').hide();
},
syncSave: function () {
$('#content').keypress(function () {
clearInterval(SomeOtherClass.autoSave);
SomeOtherClass.autoSave = setInterval(function () {
$('#flash-message').show();
$('#flash-message').delay(1000).fadeOut('slow');
}, 500);
});
},
listenForClick: function () {
$('#click-me').click(function () {
console.log(SomeOtherClass.autoSave);
clearInterval(SomeOtherClass.autoSave);
});
}
};
var SomeOtherClass = {
autoSave: null
};
ObjectClass.initialize();
ObjectClass.syncSave();
ObjectClass.listenForClick();
What you need to do is use a timeout instead of an interval, like this:
var ObjectClass = {
initialize: function() {
$('#flash-message').hide();
},
syncSave: function() {
$('#content').keypress(function(){
SomeOtherClass.autoSave = setTimeout( function(){
$('#flash-message').show();
$('#flash-message').delay(1000).fadeOut('slow');
}, 500);
});
},
listenForClick: function() {
$('#click-me').click(function() {
console.log(SomeOtherClass.autoSave);
if(typeof SomeOtherClass.autoSave === 'number'){
clearTimeout(SomeOtherClass.autoSave);
SomeOtherClass.autoSave = 0;
}
});
}
};
var SomeOtherClass = {
autoSave: 0
};
ObjectClass.initialize();
ObjectClass.syncSave();
ObjectClass.listenForClick();

reset javascript timer on click

I have this javascript code:
var logout_warning = 6000;
$(document).ready(function () {
window.setTimeout(function () {
$('#logout_warning').reveal();
}, logout_warning)
});
$(document).ready(function () {
window.setTimeout(function () {
alert("logout");
//location.href = "/login/logout.php?url=/index.php?r=inactivity";
}, logout_warning*2)
});
that displays a warning after 6000ms then redirects to a URL to logout a user after 12000ms
I have this a href link:
Stay Logged In
which i want to reset the time on click to stop the user from being logged out, i created this function but im not sure what to put inside it
function ResetLogoutTimer() {
}
try this:
var log_outer = window.setTimeout(function () {
alert("logout");
//location.href = "/login/logout.php?url=/index.php?r=inactivity";
}, logout_warning*2)
function ResetLogoutTimer() {
window.clearTimeout(log_outer);
}
Sorry for poor English, its my second language.
You should try:
var timeoutID = window.setTimeout(function () {
$('#logout_warning').reveal();
}, logout_warning)
and than
function ResetLogoutTimer() {
window.clearTimeout(timeoutID);
}
The docs for it https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout
One last thing, do not use w3c schools for learning javascript (the docs are not complete , instead use mdn site https://developer.mozilla.org/pl/docs/JavaScript

How to auto refresh HTML only if there has been no activity on a page?

I have a website which I would like to auto refresh ONLY if user is not using it for a specific time (ie.180 sec).Is there a way to auto refresh HTML only if there has been no activity on a page?
Thank you!
Two approaches:
1. Use a once-a-second timer and a "timeout" value.
You probably want to wrap this up in an object:
var activityHandler = (function() {
var timerHandle = 0,
timeout;
flagActivity();
function start() {
stop();
flagActivity();
timerHandle = setInterval(tick, 1000);
}
function stop() {
if (timerHandle != 0) {
clearInterval(timerHandle);
timerHandle = 0;
}
}
function flagActivity() {
timeout = new Date() + 180000;
}
function tick() {
if (new Date() > timeout) {
stop();
location.reload();
}
}
return {
start: start,
stop: stop,
flagActivity: flagActivity
};
})();
Then start it on page load:
activityHandler.start();
And ping it every time you see "activity":
activityHandler.flagActivity();
So for instance, you might do this:
if (document.addEventListener) {
document.addEventListener('mousemove', activityHandler.flagActivity, false);
}
else if (document.attachEvent) {
document.attachEvent('onmousemove', activityHandler.flagActivity);
}
else {
document.onmousemove = activityHandler.flagActivity;
}
2. Use a timer you reset every time there's "activity".
This is less ongoing work (we don't have something happening every second), but more work when you flag that activity has happened.
Set up a timer to do the refresh:
var handle = setTimeout(function() {
location.reload();
}, 180000);
...and then cancel and reschedule any time you see whatever you consider to be "activity":
clearTimeout(handle);
handle = setTimeout(...);
You can wrap this up in a function:
var inactivityTimerReset = (function() {
var handle = 0;
function reset() {
if (handle != 0) {
clearTimeout(handle);
}
handle = setTimeout(tick, 180000);
}
function tick() {
location.reload();
}
return reset;
})();
// Kick start
inactivityTimerReset();
// ...and anywhere you see what you consider to be activity, call it
// again
inactivityTimerReset();
Then, again, ping it on every activity. But this is a lot more work than I'd put in a mousemove handler, hence solution #1 above.
var docTimeOut;
function bodyTimeOut()
{
docTimeOut=setTimeout(function(){location.reload();},18000);
}
function resetTimeOut()
{
clearTimeout(docTimeOut);
bodyTimeOut();
}
document.onload = bodyTimeOut;
document.body.onmouseover= resetTimeOut;
you could declare a variable pageActive or something, set it to false, and whenever user does something set it to true.
Then, set a function to execute periodically as frequently as you want with setinterval() that checks this variable, if it's true set it to false to start again, if is false then refresh page.
You can use onblur and onfocus on body element to see if there is a kind of activity on your page.

Categories

Resources