Button to refresh page every second/minute etc? - javascript

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

Related

How to use setInterval to have Refresh on by default but off with a switch

I would like to use setInterval to control a refresh of my page. I would like to have it running by default (on when the page loads) but I need to be able to turn it off at certain times. So I've written what you see below. The problem is that the refresh is not on when the page first displays. It only comes on after I click the button twice to re-activate the update the setInterval controls.
My html button definition looks like this;
<button id="autoref" type="button" name="autoref" onclick="stopAutoRef();">Stop Auto Ref</button>
My stopAutoRef function looks like this;
function stopAutoRef() {
if ($("#autoref").text() == "Stop Auto Ref") {
$("#autoref").html('Start Auto Ref'); // You see this if Refresh is not automatically happening
clearInterval();
}else {$("#autoref").html('Stop Auto Ref'); // You see this if Refresh is automatically happening
setInterval(function() {showActivities(document.getElementById("select1").value);}, 60000);
}
}
setInterval returns an ID which must be passed to clearInterval to stop it. You'd also want to call your function, startAutoRef(), immediately in addition to on click to initiate the default behavior of refreshing.
var autoRefId = null;
function stopAutoRef() {
if (autoRefId !== null) {
$("#autoref").html('Start Auto Ref'); // You see this if Refresh is not automatically happening
clearInterval(autoRefId);
autoRefId = null;
} else {
$("#autoref").html('Stop Auto Ref'); // You see this if Refresh is automatically happening
autoRefId = setInterval(function() {showActivities(document.getElementById("select1").value);}, 60000);
}
}
stopAutoRef();
clearinterval generally requires a argument of which function to stop. so try this maybe?
try this:
HTML:
<button id = 'b' onclick = 'stop(this)' value = 'true'>Stop ref</button>
Javascript:
var myfunc = setInterval(function(){
location.reload();
},1000);;
function stop(button){
if(button.innerHTML == 'Stop ref'){
button.innerHTML = 'Start ref';
clearInterval(myfunc);
}
else{
button.innerHTML = 'Stop ref';
myfunc = setInterval(function(){
location.reload();
},1000);;
}
}

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

Prevent Javascript Page Reload

I am using this javascript to auto refresh a page every 30 seconds.
<script type="text/javascript">
window.setTimeout(function(){ document.location.reload(true); }, 30000);
</script>
I need to give users an option to disable this function at any time before the page is reloaded.
Note: this is for an admin panel, not a public website, and the requirement from the client is that the page auto refreshes, with an option to stop the refresh before it happens by clicking a button.
Is there any way to achieve this... That is.. disable the javascript before it executes?
clearTimeout() : Cancels a timeout previously established by calling setTimeout().
You're searching for clearTimeout() :
var refresh = window.setTimeout(function(){ document.location.reload(true); }, 30000);
$('body').on('click', '#my-button', function(){
clearTimeout(refresh);
})
Hope this helps.
Do it this way:
var myVar;
function myFunction() {
myVar = window.setTimeout(function(){ document.location.reload(true); }, 30000);
}
function myStopFunction() {
clearTimeout(myVar);
}
You just have to call the myStopFunction in order to stop the auto reload.
Do the following:
reload = window.setTimeout(function(){ document.location.reload(true); }, 30000);
Or, if using jQuery,
$("#non-reload-button").click(function(){
clearTimeOut(reload)
});
Below is code that will continue to execute every 500ms until you click the button to stop it. Just replace the 500 with the time you want and replace the console.log with what ever operation you wish to run. Hope this helps!
let auto_refresh_active = true;
const refresh = () => {
window.setTimeout(e => {
console.log('Hey, I am running! Click the button to stop me!')
if(auto_refresh_active == true) refresh();
}, 500)
}
refresh();
document.querySelector('button').addEventListener('click', e => auto_refresh_active = false);
<button>stop running</button>

AS3 - Using ExernalInterface.call To Reset JS Timer

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.

How to create timer in my case?

I am trying to have my button doing two things.
init a timer to call a function
call the same function
I have something like the following
test.prototype.setupEvent= function(){
var instance = this;
$('#btn').on('click', function(){
clearInterval(instance.timer);
this.showStuff()
instance.timer=setInterval(function(){
instance.showStuff()
},10000);
})
}
test.prototype.showStuff= function(btnID){
//jump to another page
}
My problem is that I want the user be able to see some contents after 10 second when they first click it, however, if they click the button again before 10 second is up, they can see the contents too. I am not sure how to distinguish the two different states with one click event. Can anyone help me out? Thanks!
Try
test.prototype.setupEvent = function () {
var instance = this;
$('#btn').on('click', function () {
//if there is a timer running then clear the timer, show the content and delete the timer reference
if (instance.timer) {
clearInterval(instance.timer);
instance.showStuff();
delete instance.timer
return;
}
//also you may want to use setTimeout() not setInverval()
instance.timer = setInterval(function () {
instance.showStuff();
delete instance.timer
}, 10000);
})
}
test.prototype.showStuff = function (btnID) {
//jump to another page
}

Categories