Hey guys I have a javascript function that keeps persisting even when navigating to another page (single page templates not multipage) in Jquery Mobile
<script type="text/javascript">
setInterval("window.location.reload();", 5000);
</script>
How do I ensure that this only occurs on the page from which it is called rather than it calling it on every page I link to with ajax based navigation?
I am using Jquery Mobile 1.2
Bind it to the page where you want it to occur. Replace $('.selector') with pageID, e.g. $('#home'). You could also be more specific $('div[data-role="page"]#PageID').
// Trigger interval
$('.selector').bind('pageinit', function () {
setInterval("window.location.reload();", 5000);
});
// Stop interval when navigating away
$('.selector').bind('pagehide', function () {
clearInterval();
});
How do I ensure that this only occurs on the page from which it is
called rather than it calling it on every page I link to with ajax
based navigation?
Don't call it? Currently your code is set up to always run when it's included on the page. Either don't include it or prevent it from running in some other way (such as an if-statement).
You could clear the interval just before you navigate.
First you need to get a reference to the interval when you create it:
var intervalRef = setInterval("window.location.reload();", 5000);
Then you can clear it like this:
clearInterval(intervalRef);
// Navigate
Just cancel your timeout when the other page loads, or when the current page exits (the other page loads in ajax so the timed interval stays up).
// trigger
myInterval = setInterval("window.location.reload();", 5000);
// stop
clearInterval(myInterval);
Related
I have 2 pages, Home page and Edit page.
I used a function which will auto log out the user after a certain amount of time of inactivity.
The function is only used in Home page and not Edit page.
Below is the function code.
// Set timeout variables.
var timoutWarning = 10000;
var timoutNow = 30000;
var warningTimer;
var timeoutTimer;
// Start timers.
function StartTimers() {
console.log("Start TImer");
warningTimer = setTimeout("IdleWarning()", timoutWarning);
timeoutTimer = setTimeout("SignOut()", timoutNow);
$( "#timeout" ).dialog({
autoOpen: false
});
}
// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(timeoutTimer);
StartTimers();
$( "#timeout" ).dialog("close")
console.log("Reset TImer");
}
// Show idle timeout warning dialog.
function IdleWarning() {
$("#timeout").dialog({
autoOpen: true,
modal: true
});
}
I called out the function in the Home page by using
<body onload="StartTimers();" onmousemove="ResetTimers();">
<div id="timeout">
<h1>
Session About To Timeout</h1>
<p>
You will be automatically logged out in a while<br />
To remain logged in move your mouse
</div>
The timer works perfectly fine in the Home page, but after I switch to Edit page ( without the function basically an empty page), I will still get auto log out with or without moving the mouse.
Does that means that the function is still running even after I switch page? If so, is there anything I can do to stop the timer after I switched the page?
p.s I did tried adding in the function and call it in the Edit page, however, even after I kept on moving my mouse I will still get logged out which is why I assume that the function is still running after I switch page.
SOLVED : its working fine right now after I restart my browser. I believe I might have screwed up somewhere. I apologize to people who invested their time into this question. The answer to my question based on the comments/answers below is NO. setTimeout DOES NOT continues after changing page.
If the browser has fully loaded the second page, and that code isn't on it, that code won't run. That's assuming you're loading the second page 'traditionally' and not pulling it in via AJAX.
I would do the following things:
Put an alert("Code running") in the setTimeout function. That's a very simple way of telling you if the code is running or not.
Check the source code for your edit page. Make sure you haven't duplicated the code to that page too.
No, timeouts get deleted when you close/refresh the page (just like anything in JavaScript). So your bug must be something else.
I'm having a problem always when I try to use the following code in a button in my HTML file.
onClick=window.location.reload();
mapGenerator();
The page reloads but the javascript (mapGenerator) that make a D3JS view doesn't appear. What am I doing wrong?
location.reload() will immediately reload the page and prevent any following code to execute.
You can, however, create a function that executes your method after the page has (re)loaded:
window.onload = function() {
mapGenerator();
};
This method will run every time the page has fully loaded. To only run the code after you have reloaded the page using location.reload(), you could create a method that handles the click by setting a cookie and then reloading the page.
function handleClick() {
document.cookie="reload=true";
location.reload();
}
This would require you to change your onClick value to onClick="handleClick();". Now, whenever the page loads, you can check whether the cookie has been set. Your window.onload function now changes to this:
window.onload = function() {
if(document.cookie.indexOf("reload") >= 0) {
mapGenerator();
}
}
Checking if a cookie exists - answer by Michael Berkowski
After the reload it's up to you whether you want to unset the cookie — if you don't, the page will run the function mapGenerator on every page load until the cookie expires.
If you need more help with cookies, check out W3Schools' tutorial.
As per your description mentioned above two actions are to be taken on click. As the first action reloads the page the second action is lost. If you want any action to be taken on load of the page, mention the same on onload event of the page.
Hopefully a simple question; if I create a timer using JavaScript embedded within my page, and I then navigate away from that page, will the timer be automatically cancelled or will it continue to run?
EDIT
Expanding the question, if that page were to perform a post-back (in my case, this is ASP.NET Forms), and the script is rendered as a part of the page markup, would the original timer created when the form is first displayed be cancelled during that post-back or would a second timer be created?
Example (rough typed):
<body>
...
<script type='text/javascript'>
function doSomething() { ... }
x = setInterval(doSomething(), 60000);
</script>
...
<button type="submit" />
...
</body>
Following the post-back, a new timer will be created as a result of the page being re-rendered, how many timers are now running (assuming the post-back was within the interval specified by the timer)?
It'll be automatically cancelled. JavaScript code is executed within the context of a page.
Think about a page like an application. Switching to other page is like closing an application and opening a new one. This also applies to a full page refresh (i.e. when you press F5).
I have a button which acts as an indicator, so has two states; pressing it toggles the state, and moves on to the next page.
Pressing the button calls a JavaScript function which handles this.
Having changed a button's 'src' image, using jQuery, I wish for the user to see the image change, pause for a fraction of a second, and only then see the next page displayed.
I am finding that the image does not visibly change until the JavaScript function returns, but this is after the pause, and after the page change. I.e. the browser does not show the page changes until the button's function has exit.
So I wish to cause the page to repaint in the browser, before the pause.
All the solutions I have tried refresh the page to its state on the server, and any changes I made to it in jQuery are lost.
Is there a way to force the page or button to be repainted, which will honor the changes I made to it in JavaScript/jQuery?
$("#YourButtonWhichTriggersChanges").click(function() {
// page repaint code, image change, etc.
setTimeout(function(){
window.location.reload();
// use window.location.href = "my/new/url.html";
// or window.location.replace("my/new/url.html");
// to change the page instead of just reloading.
}, 1000);
});
Where 1000 is the number of milliseconds you want to wait before refreshing the page.
Edit: I think you want this code instead:
$("#ApproveButton").css('backgroundImage', 'url(\'img/but/proof/ApprovePageButton.png\')');
The extra backslashes are in there to escape out the single quotes in the url parameter.
Another edit: Here's a combination of the two solutions I supplied which should work:
$("#ApproveButton").click(function() {
// actually repaint the button's background image
$(this).css('backgroundImage', 'url(\'img/but/proof/ApprovePageButton.png\')');
// change the page after 1000 milliseconds have gone by.
setTimeout(function(){
window.location.reload();
/* use window.location.href = "my/new/url.html";
* or window.location.replace("my/new/url.html");
* to change the page instead of just reloading.
*/
}, 1000);
});
I'm building a simple Facebook tab. I have two tabs that change every 3 seconds with with the help of setInterval and JQuery until the user interacts with them. Which them cancels the switching.
$(document).ready(function() {
$('#item2').hide();
$('li#tab1').addClass('selected');
var timer = setInterval(function () {
$('div.item').fadeToggle('fast')
$('li.tab').toggleClass('selected') ;
}, 3000);
$(window).blur(function(){
clearInterval(timer)
})
// setup. Set the first tab to selected
$('li.tab').click(function(event) {
clearInterval(timer);
$('li.tab').toggleClass('selected')
$('div.item').fadeToggle('fast')
});
});
This works fine... mostly. The problem occurs when I lose focus on the page for a while ( 2-3 minutes ) and switch back, the tabs switch back and forth very fast for a while before returning to normal. I am able to fix this issue if NOT in an iframe with:
$(window).blur(function(){
clearInterval(timer)
})
which just stops the switch altogether. But this does not work when the page is inside a iframe on Facebook. Can anyone suggest a solution?
Try using setTimeout instead of setInterval.
function doStuff(){
//do some stuff
setTimeout(doStuff, timeout);
}
setTimeout(doStuff, timeout);
This way, you only have one iteration going in the background, so it'll flash once immediately when the user switches back to the page (hopefully fast enough that he doesn't notice).