How can stop a website (game) from refreshing when inactive - javascript

I never did anything in Coding but this game i play refreshes every 3 min when inactive (spectating) i want to stop this or edit its script. It also refreshes when opening the DevTools in Chrome.
it script is external
<script src="assets/js/new_main_out1.js?461"></script>
window.lastDeath = Date.now()
window.playing = false
window.interval = setInterval(function() {
if (!window.playing) {
if ((Date.now() - window.lastDeath) > 3*60*1000) {
document.location.href = "https://game.com/landing/"
}
}
}, 10*1000)

You could continually reset window.lastDeath to within the last minute:
setInterval(() => {
window.lastDeath = Date.now();
}, 60000);
You could also monkeypatch window.setInterval to detect if the page's function is passed, and if it is, ignore it (and start the interval normally otherwise).

Related

JS added in bookmark still running after refreshing page

I'm running a JS code from a bookmark (on opera browser). I created an endless timer countdown which resfreshes my page every 10secs. It just fine in my .html file. But when i'm using it like a bookmark in any other site it works only 1 time and then it stops.
How could it be able to run after the refresh?
javascript:
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
location.assign(location.href.split('#')[0]);
clearInterval(ticker);
startTimer(1*10);
}
}
startTimer(1*10);
You don't need an interval. As soon as you reload the page, the interval is cleared. As soon as the page is reloaded, your code executes again.
Try this instead:
document.body.innerHTML = Math.random(); // Demonstrates the page reload
setTimeout(() => document.location.reload(), 1000);

Chrome timer extension - how to keep timer running even when extension is closed?

I'm working on my first extension - Tea timer. After choosing a tea type/entering number of minutes timer will start running. The problem is that when I change my tab or close the extension, the timer will stop running although I would like it to run in the background. I'm not sure how to handle this with chrome.storage.
Here is my timer.js:
function timer(seconds) {
clearInterval(countdown);
const now = Date.now();
const then = now + seconds * 1000;
displayTimeLeft(seconds);
displayEndTime(then);
countdown = setInterval(() => {
const secondsLeft = Math.round((then - Date.now()) / 1000);
if (secondsLeft < 0) {
clearInterval(countdown);
const soundEffect = new Audio("tibetan.mp3");
soundEffect.play();
setTimeout(function() {
alert("Your tea is ready!");
}, 500);
return;
}
displayTimeLeft(secondsLeft);
}, 1000);
}
function displayTimeLeft(seconds) {
const minutes = Math.floor(seconds / 60);
const remainderSeconds = seconds % 60;
const display = `${minutes}:${
remainderSeconds < 10 ? "0" : ""
}${remainderSeconds}`;
if (timerDisplay) {
timerDisplay.textContent = display;
}
//console.log({ minutes, remainderSeconds });
}
function startTimer() {
const seconds = parseInt(this.dataset.time);
console.log(seconds);
timer(seconds);
}
buttons.forEach(button => button.addEventListener("click", startTimer));
background.js
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([
{
conditions: [new chrome.declarativeContent.PageStateMatcher({})],
actions: [new chrome.declarativeContent.ShowAction()]
}
]);
});
});
Thank you all in advance!
Since time.js is part of a pop-up window, the code in that file (as well as the interval you've set using setInterval) will stop running as soon as the pop-up window is closed.
In order to make this work, you'll have to move the interval to the background page, the background page's context can be set to stay on as long as the browser is opened.
By the way, the code that is currently in background.js doesn't do anything and you only need something like that if you want to use page actions
Here is my approach for doing that:
background.js
let timerID;
let timerTime;
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.cmd === 'START_TIMER') {
timerTime = new Date(request.when);
timerID = setTimeout(() => {
// the time is app, alert the user.
}, timerTime.getTime() - Date.now());
} else if (request.cmd === 'GET_TIME') {
sendResponse({ time: timerTime });
}
});
timer.js
// Call this when the pop-up is shown
chrome.runtime.sendMessage({ cmd: 'GET_TIME' }, response => {
if (response.time) {
const time = new Date(response.time);
startTimer(time)
}
});
functions startTimer(time) {
if (time.getTime() > Date.now()) {
setInterval(() => {
// display the remaining time
}, 1000)
}
}
function startTime(time) {
chrome.runtime.sendMessage({ cmd: 'START_TIMER', when: time });
startTimer(time);
}
Essentially, when the user starts a timer, you send a message to the background script with a future date for when the timer is done. Then, in the background script you set a timeout to be triggered at that date so you can do something (play a sound) even if the pop-up window is closed.
Then, when the pop-up window is reopened, you send a message to the background script and it will send back the date for the timer that was previously set.
This can be improved, for now, this will work correctly as long as the browser is opened for the entire length of the timer, to make it work even if the browser is closed and reopened, you can save and restore the timer's date from storage.
Move the setInterval() code to background script and change "Persistent" property for background script in manifest to "True"
This allows extension to continue running background script even if the popup window of extension is closed and setInterval() will continue to run.
NOTE: You should be careful when you change "Persistent" property to "True". Make sure chrome webstore allows it without any issues.

Javascript countdown timer is erratic

I have a raspberry pi that initiates a garage door close event after a 90s delay. I have been successful in showing the countdown timer dynamically update on a web page but for some reason the countdown is erratic and constantly flickers with lower and then higher numbers.
Clearly I must be refreshing something but needless to say I have spent many hours on forums but to no avail. I am hoping that someone can look at my code and give me some direction.
<?php
$pinInput = trim(shell_exec("gpio read 26"));
$pinOutput = trim(shell_exec("gpio read 2"));
if ($pinInput!=$pinOutput){
echo "Timing for auto reclose...";
?>
<br>
<b><span id="countdown">90</span> Seconds</b>
<script type="text/javascript">
var timer = 90,
el = document.getElementById('countdown');
(function t_minus() {
'use strict';
el.innerHTML = timer--;
if (timer >= 0) {
setTimeout(function () {
t_minus();
}, 1000);
} else {
// do stuff, countdown has finished.
}
}());
</script>
<?php
}
elseif ($pinInput=1)
{
echo "Monitoring input...";
}
else
{
echo "Garage door is closing...";
}
?>
I should also mentioned that the above piece of code is within a file called timing.php. This is called on index.php as follows:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#Input').load('timing.php');
}, 1000); // refresh every 1000 milliseconds
</script>
So in summary, what I would like is for "Timing for auto recluse..." to remain static if ($pinInput!=$pinOutput) but dynamically shown the countdown from 90s.
First let's look at this code, the last bit in your question:
var auto_refresh = setInterval(
function () {
$('#Input').load('timing.php');
}, 1000); // refresh every 1000 milliseconds
That sets up an interval timer that will load the "timing.php" URL into the page once per second.
Now, here's part of what you say is returned from "timing.php":
var timer = 90,
el = document.getElementById('countdown');
(function t_minus() {
'use strict';
el.innerHTML = timer--;
if (timer >= 0) {
setTimeout(function () {
t_minus();
}, 1000);
} else {
// do stuff, countdown has finished.
}
}());
So when the browser receives the response from "timer.php", jQuery will run that code. That sets up a repeating timer function — essentially the same thing as an interval timer, except that it stops itself after a while).
Now, when that code is reloaded, you don't get new global variables timer and el. The global variables already defined by the last load of "timer.php" will simply have their values overridden. That means that the already-in-process previous timeout sequence will suddenly see timer set back to 90.
It's not clear exactly what it is you intend to do. Perhaps that setInterval() is just superfluous, and all you need to do is just load "timeout.php" once. Or, perhaps when the "timeout.php" code loads, it first needs to wipe out any already-running timeout loops, though that seems odd since those are set up to wind down only after 90 seconds.

How to make a warning to user when 10 secs. to refresh setInterval?

I am using setInterval to refresh a content of graph in page. How to make a show an alert to user when setinterval is about to refresh that 'the content will be refreshed'.
For example my interval is using 300 secs and I want to show an alert after 290 seconds have passed that 'The content will be refreshed after 10 secs. Do you want to refresh the graph' for each interval. How to do this? Any suggestions?
You should set you interval to 290000ms, and then it will show an alert, and then you use setTimeout to update your page after 10 seconds, like so:
setInterval(function() {
alert("10 seconds to update")
setTimeout(function() {
//REFRESH PAGE
},5000);
}, 10000);
On your page loading you can put your 290 secs refresh
setInterval(function(){
showDialogBox("do you want to refresh");
}, 290000);
and then add a action on the confirm button that will be delayed the last 10sec
confirmButtonOnClick(){
setInterval(function(){
refresh();
}, 10000);
}
In cases like this, I prefer to use setTimeout over setInterval as it gives better control.
So I set two timers -- one for the warning and then another for the timeout itself, then I restart the two timers.
const timeoutWarning = 1800;
const timeoutDone = 2000;
function showWarning() {
console.log('About to time out...');
}
function doTimeout() {
console.log('Timeout reached');
setWarnings();
}
function setWarnings() {
setTimeout(showWarning, timeoutWarning);
setTimeout(doTimeout, timeoutDone);
}
setWarnings();
Something like that:
var interval;
var secondsPassed = 0;
function refreshWithMessage() {
interval = setInterval(function(){
if(secondsPassed == 290) {
//showMessage with options
}
if(secondsPassed == 300) {
clearInterval(interval);
//do what you need here (refresh page?)
}
secondsPassed++;
}, 1000)
}
If you need to let user cancel the interval - you should just clear interval and then reset seconds variable to 0.

javascript autologout for inactivity for 10 minutes

hello all i am writing a code for auto logout for inactivity for about 20 minutes which should interact with keyboard as well as mouse and i have following code which works for most of the function but it is not resetting the timer for mouse movement and keyboard activity.
var timoutWarning = 9000; // Display warning in 14 Mins.
var timoutNow = 9000; // Warning has been shown, give the user 1 minute to interact
var logoutUrl = 'logout.php'; // URL to logout page.
var warningTimer;
var timeoutTimer;
// Start warning timer.
function StartWarningTimer() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
}
// Reset timers.
function ResetTimeOutTimer() {
clearTimeout(timeoutTimer);
StartWarningTimer();
$("#timeout").hide();
}
// Show idle timeout warning dialog.
function IdleWarning() {
clearTimeout(warningTimer);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
$("#timeout").show();
}
// Logout the user.
function IdleTimeout() {
window.location = logoutUrl;
}
$( document ).ready(function() {
StartWarningTimer();
});
$('html').mousemove(function() {
ResetTimeOutTimer();
});
i want the code should intract with mouse movement and keyboard press
all kind of help is appreciated please suggest me something
At first, you should not use setTimeout this way - inactive tabs getting slower, so there's no guarantee that your code will be executed in 14 minute. The better way to do that is to check repeatedly the elapsed time.
var startTime = +new Date();
function checkForWarning () {
if (+new Date() - startTime > maxInactiveTime) {
// show warning
}
}
You can track activity this way:
$(document)
.on('click', ResetTimeOutTimer)
.on('mousemove', ResetTimeOutTimer);
Hope it helps.

Categories