AS3 - Using ExernalInterface.call To Reset JS Timer - javascript

I'm trying to build a 'dead mans switch' into a flash app. When the app crashes, or slows down significantly, I would like the webpage to refresh. From what I've read and seen here, it's possible to use ExernalInterface to call a resetTimer JS function.
Heres my AS3..
//External Timer and Handler
var externaltimer: Timer = new Timer(1000);
externaltimer.addEventListener(TimerEvent.TIMER, callTimerJS);
externaltimer.start();
function callTimerJS(event : Event):void{
ExternalInterface.call("window.clearTimeout");
ExternalInterface.call("timeoutHandle");
}
Heres my JS in my HTML page...
var timeoutHandle = window.setTimeout(function() {
window.location.reload(1);
}, 15000);
window.clearTimeout(timeoutHandle);
timeoutHandle = window.setTimeout(function() {
window.location.reload(1);
}, 15000);
I'm not sure how to test this to verify it's working. I do know when I build, the webpage refreshes every 15 seconds. I'm not able to get flash to reset the timer.

Use normal function-declarations and be sure that is not a js-core-function-name.
You can call only functions.
AS
//External Timer and Handler
var externaltimer: Timer = new Timer(1000);
externaltimer.addEventListener(TimerEvent.TIMER, callTimerJS);
externaltimer.start();
function callTimerJS(event : Event):void{
if (ExternalInterface.available) {
ExternalInterface.call("clearTimeoutfromExtern");
}
}
JS
var timeoutHandle;
function clearTimeoutfromExtern(){
clearTimeout(timeoutHandle);
timeoutHandle = setTimeout(refresh, 15000);
}
function refresh(){
window.location.reload(1);
}
I just wrote it here in the editor...
Greetings.

Related

Javascript not executing immediately, delayed until a second after page load

After a quick cobbling together of a clock app to test the JavaScript linking ability of my Flask App hosted on Heroku, I'm stumbling on the clock text not immediately filling the .innerHTML of my element.
Javascript:
// This sets our ticker to execute the function once a second.
var myVar = setInterval(function() {
myTimer();
}, 1000);
function myTimer() {
var d = new Date();
document.getElementById("clock").innerHTML = d.toLocaleTimeString();
}
The HTML is very simple, just a small h4 element with the id of "clock". I've tried document.onload as well, but whatever I try, the website loads with an empty element then fills it about one second later.
While I have your attention, why is the standard procedure for setting an interval declaring it as a variable? Is it for later reference in the program? Would it work as a naked setInterval(xxxxx);?
Thank you in advance!
setInterval runs the funtion after a specified delay, if you would like to display time on window load for example, you could call your function once in window.onload. Declaring as a variable is needed if you would like to clear the interval, I added a button as an example.
window.onload = () => {
myTimer();
}
const btnStop = document.getElementById("btn-stop");
btnStop.addEventListener('click', () => {
console.log('stopped');
clearInterval(myInterval);
})
var myInterval = setInterval(function() {
myTimer();
}, 1000);
function myTimer() {
var d = new Date();
document.getElementById("clock").innerHTML = d.toLocaleTimeString();
}
<p id="clock"></p>
<button id="btn-stop">stop</button>

clearInterval not working in javascript chrome extension

I'm trying to make a chrome extension and in my content script which runs only on www.youtube.com it's supposed to check, document.getElementById("movie_player"), if a particular div element has loaded or not. If not setInterval and wait a second. If it has loaded then run alert("Hello") and clearInterval which will end the script.
However, it's not working. Even after I find the element, and it says "Hello" it continues to say hello which means setInterval is still calling my function after 1000 milliseconds even though it should have been cleared.
Here's my content.js file:
var timeOut;
function CheckDOMChange()
{
moviePlayer = document.getElementById("movie_player");
if(moviePlayer !== null)
{
WhenVideoLoads();
}
timeOut = setInterval("CheckDOMChange();", 1000);
}
function WhenVideoLoads()
{
alert("Hello");
clearInterval(timeOut);
}
CheckDOMChange();
As you can see, I made timeOut a global variable so it shouldn't be a scope problem. So I really don't know what the problem is because the condition is being met and clearInterval is being called.
Any help would be much appreciated.
The issue is that you have setInterval inside the function. Basically, for every call you are setting interval which creates multiple setIntervals. Remove the setInterval from within the function
var timeOut;
function CheckDOMChange() {
moviePlayer = document.getElementById("movie_player");
if (moviePlayer !== null) {
WhenVideoLoads();
}
}
function WhenVideoLoads() {
alert("Hello");
clearInterval(timeOut);
}
timeOut = setInterval("CheckDOMChange();", 1000);
By calling CheckDOMChange recursively, you are actually exponentially creating timers, and you are only clearing the last timer when calling WhenVideoLoads.
You may try to run this snippet and inspect the console to see what is happening, and see that clicking the button will clear the last timer but not all those that have been created before.
var timeOut;
var counter = 0;
function CheckDOMChange()
{
console.log("counter :", counter);
if (counter > 16) {
console.log("Stop creating new timers!");
return;
}
timeOut = setInterval("CheckDOMChange();", 5000);
console.log("timeOut :", timeOut);
counter ++;
}
function WhenVideoLoads()
{
console.log("Clearing ", timeOut);
clearInterval(timeOut);
}
CheckDOMChange();
<button onclick="WhenVideoLoads()" id="clear">Clear timer</button>
You should avoid calling CheckDOMChange recursively, and proceed as #cdoshi suggested.
Hope this helps!

Boolean statement not evaluating in javascript

I'm writing a script, and there are two boolean statements that are very similar but giving different results, and I don't see why they conflict with one another.
My function looks like this:
SCRIPT:
(function() {
window.onload = function() {
let stopped = true;
let button = document.getElementById("start-stop");
if (stopped) {
setInterval(function() {
console.log("The timer is working.");
}, 1000);
}
button.addEventListener('click', function(){
if (stopped) {
stopped = false;
console.log(stopped);
} else {
stopped = true;
console.log(stopped);
}
});
}
}
}).call(this);
The basic idea is that when I push the button the setInterval function stops, however it keeps on going even when the if/else function switches stopped to false.
For example, my console.log looks like this:
I.e. stopped = false, but setInterval doesn't terminate.
Why is this not evaluating correctly?
The problem with your code is that you are trying to work on a piece of code that has already started to operate. In simpler words, the setInterval method will be called every 1000ms, no matter what the value of stopped variable is. If you wish to really stop the log, you can do any of these:
clearInterval()
to completely remove the interval or
setInterval(function() {
if (stopped) {
console.log("The timer is working.");
}
}, 1000);
to check if the value of stopped variable has changed or not (after the click) and act accordingly. Choose either of these for your purpose..
you are calling setinterval even before button is clicked .As the event is already triggered you cannot stop just by setting the variable to false ,you need to clear the interval using clearinterval
check the following snippet
var intervalId;
window.onload = function() {
let stopped = true;
let button = document.getElementById("start-stop");
var Interval_id;
button.addEventListener('click', function() {
if (stopped) {
Interval_id = callTimeout();
stopped = false;
} else {
clearInterval(Interval_id);
stopped = true;
}
});
}
function callTimeout() {
intervalId = setInterval(function() {
console.log("The timer is working.");
}, 1000);
return intervalId;
}
<input type="button" id="start-stop" value="click it">
Hope it helps
Put the if(stopped) statement inside the setInterval function because if you used this function once it will keep going..
Another way to stop setInterval function is by using clearInterval, like this
var intervalId = setInterval(function() { /* code here */}, 1000)
// And whenever you want to stop it
clearInterval(intervalId);
When you click the button stopped variable becomes false but the setInterval will not stop because the setInterval code is already executed.. it will not execute again on button click. And if you reload the page what will happen is that stopped variable will be again set to true as you have written at first line and setInterval will execute again ..
Now What you can do is store setInterval in a variable like this
var timer = setInterval(function,1000);
and then when you click the button use this method to clear interval
clearInterval(timer);
this should do the trick .. Hope it helps ..

how to stop a Javascript function when the user switch tab or minimize the broswer

I'm creating a chat that need to retrieve messages from PHP using AJAX in intervals. The problem is that the users can open multiple tab of different chatroom, and that's going to take a a lot of resource from the server. So, how can I stop a function in the other tabs when the user switches page, then reactive it when they return to the tab. I'm new to coding so please keep the code as simple as possible (NO jQuery please.)
Here is an function test I was trying, but no luck:
function window_active(){
window.onfocus = function() {
test()
};
window.onblur = function() {
//stop the script OR change the setTimeout so the functon run less.
};
}
function test(){
alert('adadasdad');
setTimeout(function(){}, 10000);
}
Thanks in advance. (:
Update:
requestAnimationFrame() didnt work.
function loop() {
var div_id = document.getElementById('tester');
var msg = document.createTextNode("sadksadkjsahdjkasdjkahdjkas");
div_id.appendChild(msg);
setTimeout( function() {
requestAnimationFrame( function() {
loop();
} );
}, 1000 );
}
Update 2:
Counldn't find this answer anywhere, and then I got lucky and found this page with the help of ehynds answer about "document.hidden". Thanks ehynds! (:
function loop() {
//do stuff.
setTimeout( function() {
if(document.hasFocus()){
//"document.hasFocus()" return **true** only if your on the tab.
loop();
}
}, 1000);
window.onfocus = function() {
//reactivted the function.
loop();
};
}
Hopes this help someone looking for the answer. (:
HTML5 visibility API:
document.addEventListener('visibilitychange', function() {
document.hidden; // whether or not the tab is visible
});

Button to refresh page every second/minute etc?

I'm wanting a button that when clicked will refresh the current page after a specified amount of time.
I currently have:
<script type="text/javascript">
setTimeout(function reload(){
location = ''
},1000)
</script>
<button onclick="reload()">Reload</button>
However, that JUST reloads the page without even having to click the button. I'm wanting the button to execute the script, and also a button to STOP the page reload.
This should be really simple but I can't figure it out :(
******EDIT**********
I'd also like the script to run on an infinite loop after the button is clicked.
Your setTimeout is called on page load. You need to put it inside the reload() function:
function reload() {
setTimeout(function() {
window.location.reload();
}, 1000);
}
To make the timer run every x seconds and reload only a part of the page you would need to use setInterval and an AJAX request, something like this:
var timer;
function reload() {
timer = setInterval(function() {
$.post('foo.html', function(data) {
$('#bar').html(data);
});
}, 1000);
}
function clear() {
clearInterval(timer);
}
This should do the trick
<script type="text/javascript">
function reload(){
setTimeout(function(){location.reload()}, 3000);
}
</script>
<button onclick="reload()">Reload</button>
What you wrote is
window.setTimeout("location = ''"; ,1000);
You were saying execute this function after 1 second. You need to define the setTimeout inside the function. Also there is a built in method to reload the page. Call that instead of setting the location to a blank string.
function reload() {
setTimeout( function() {
window.location.reload(true);
},1000);
}
Now to cancel the timeout, you need to use clearTimeout(timeoutId); You get the timeoutId from the integer that the setTimeout returns when you call it.
var timer = null;
function reload() {
timer = window.setTimeout( function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
}
AND you said you want it to keep running. That will require cookies or localstorage.
var timer = null;
function reload() {
localStorage.reload = true; //set localstorage so we know to fire it off again
timer = window.setTimeout( function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
localStorage.removeItem("reload"); //remove the key in localstorage
}
if (localstorage.reload) { //check localstorage to see if key is set
reload();
}
You need to wrap the whole thing in another function and call that from the button click

Categories