JS added in bookmark still running after refreshing page - javascript

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);

Related

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

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).

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.

If Deeplink url not work send user to download page

I need to implement a javascript where I can detect if my deep link is worked or not, If it works then it should remain same but if it does not work then it must start download file.
For that, i use timeout function to do it. Here is sample code I used.
setTimeout(function () { window.location = "https://itunes.apple.com/appdir"; }, 25);
window.location = "appname://";
But this code works fine on android and ios but it is creating problem while it comes to the desktop browser. In desktop browser after Deeplink works properly, timeout function do not stops and it redirects to download page.
so finally I want some event which can detect if my Deeplink is worked or not so I can set cleartimeout function to prevent redirecting to downloading URL
I have been facing similar problem, and finally I have found a nice botched job to make it work:
var timer = null;
function setListener() {
window.document.addEventListener("visibilitychange", function(e) {
window.clearTimeout(timer);
timer = null;
window.open('','_self').close();
});
}
function redirectAndroid() {
setTimeout(function () { window.location = "https://itunes.apple.com/appdir"; }, 25);
window.location = "appname://";
}
function redirecIOS() {
setListener();
var beforeApp = new Date().valueOf();
window.location.href = "appname://";
var afterApp = new Date().valueOf();
if (afterApp - beforeApp < 100) {
setTimeout(function() {
"https://itunes.apple.com/appdir";
}, 25);
} else {
if (timer === null) {
timer = setTimeout(function() {
"https://itunes.apple.com/appdir";
}, 200);
}
}
This way, after redirecting to application, if it opens it triggers the event "visibilitychange" before the timeout function, and you clear the timeout avoiding it to redirect to web, and close the browser (if you want). If application is not installed, timeAfterApp - timeBeforeApp is not < 100 so there you set the timeout.
For desktop browser, consider using window blur listener and act accordingly
Blur listener will tell you if user left the tab or browser
window.onblur=()=>{//deeplink check (maybe unsuccessfull?)
window.onfocus=()=>{//deeplink unsucesfull};
}
I would try with a timestamp expression in the timeout.
Something like this (play around with the thresholds as needed):
var clickedTm = +new date;
setTimeout(function () {
if (+new date - clickedTm < 600) {
window.location = "https://itunes.apple.com/appdir";
}
}, 500);
window.location = "appname://";

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.

javascript timer page up and down won't go to bottom of page

I have a timer script which scrolls up and down and repositions the page to the top every 10 seconds and back down every 5 seconds. My problem is I can't get it to scroll all the way down.
<script language="JavaScript" type="text/javascript">
// Configure refresh interval (in seconds)
var refreshinterval=300
// Shall the coundown be displayed inside your status bar? Say "yes" or "no" below:
var displaycountdown="yes"
var starttime
var nowtime
var reloadseconds=0
var secondssinceloaded=0
function starttime() {
starttime=new Date()
starttime=starttime.getTime()
countdown()
}
function countdown() {
nowtime= new Date()
nowtime=nowtime.getTime()
secondssinceloaded=(nowtime-starttime)/1000
reloadseconds=Math.round(refreshinterval-secondssinceloaded)
if (refreshinterval>=secondssinceloaded) {
var timer=setTimeout("countdown()",1000)
if (displaycountdown=="yes") {
window.status="Page refreshing in "+reloadseconds+ " seconds"
}
if (timer % 5 == 0) {
window.scrollTo(0,1200);
}
if (timer % 10 == 0) {
window.scrollTo(0,0);
}
}
else {
clearTimeout(timer)
window.location.reload(true)
}
}
window.onload=starttime
</script>
How do i get it to scroll all the way down or page down?
thanks in advance
I think this is much simpler and achieves what you're looking for:
function starttime() {
setTimeout('scrollDown()',5000);
}
function scrollDown() {
window.scrollto(0, document.body.scrollHeight);
setTimeout('scrollUp()',5000);
}
function scrollUp() {
window.scrollto(0,0);
setTimeout('scrollDown()',5000);
}
window.onload = starttime
The reason your page wouldn't scroll all the way down is probably with your pixel value of 1200. This scrolls the page down 1200px, which may or may not be all the way. Heck, your page could be 10000px high or more. Try setting a limit that you can safely know you're page will never surpass, like 20000, and it should scroll all the way to the bottom. :D

Categories