JavaScript: How can I stop SetTimout reloading my page? - javascript

I have a function that sets display=none on a table row. At the end of my function I want to set a timeout to hide the next table row after a few milliseconds.
I have a problem though. When the timeout expires, the page is reloaded (undoing the effects of my function and and scrolling to page top). This even happens if I use an empty timeout: window.SetTimeout(function () { ; }, 1000); How can I stop this happening?
I am using recent Chromium.

I think your problem is somewhere else, disregarding the obvious error that you cased SetTimeout wrong ( it should be setTimeout ).
There is nothing in your code that should refresh the page.
Edit:
Just thought of something, since you cased SetTimeout wrong, maybe your click handler doesn't finish as it should, thus letting the link "pass through" and load the page.
Edit2:
Huh, thats not the case....
http://jsfiddle.net/eGhQM/6/
Edit3:
...and maybe it is(x-something error on fiddle though)
http://jsfiddle.net/eGhQM/9/

I'm not sure I 100% understand the question, but you can use clearTimeout if you store the timeout you set. That is to say:
var timeout = setTimeout(function(){
alert('Hello, world!');
}, 1000);
...
clearTimeout(timeout); // destroys the timeout, preventing it from occurring
// (assuming you call this before the time expires)

Related

Does setTimeout continues even after changing page?

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.

wait for a click and then autoclick a button after 500 ms in javascript

I'm new to JavaScript.
I'm writing a simple code to add it in a chrome extension call it Shortkeys.
I just want the code to make a simple action:
Wait for a click of the mouse and then click a button in certain positions of the screen after 500 ms...
This is what I have written until this moment but is not working:
document.addEventListener('click', TimerThenPlay);
function TimerThenPlay(e) {
setTimeout(500)
document.elementFromPoint(1175, 85).click();
stop(TimerThenPlay);
clearTimeout(TimerThenPlay);
return;
};
What I'm doing wrong?
EDIT:
I have an APP running on Chrome...
I need to Click a Link and wait 500 ms to click a button... i can do that manually but sometimes dsnt work and i have to try again..
I realize that chrome has an extension that you can inject to the page a javascript code when u press a key in your keyboard. Thats why im using Shorkeys (if u know a better extension for this, just tell me).
Well... i have assign the < key to run the code...
What i need, is that everytime that i hit the < key... Chrome waits for a click (so i have time to look for the link that i want to open with de button)...
And when i click the link, it waits 500 ms and then click the button in the position that i select ( i cant use the Button ID cause it changes every minute).
I have tried the codes above and it works for the first time.. then, i dnt know why is keeping clicking 500 ms after a make a mouse click in the next pages... How can i stop that loop in the next page?
function TimerThenPlay(e) {
setTimeout(function(){
document.elementFromPoint(1175, 85).click();
stop(TimerThenPlay);
clearTimeout(TimerThenPlay);
},500)
}
SetTimeout method takes two arguments. First is function to execute after second argument time passes.
Hope this helps
Your setTimeout syntax is wrong.
Syntax of setTimeout:
setTimeout(function(){}, time)
you need to update your setTimeout function
function TimerThenPlay(e) {
setTimeout(function(){
document.elementFromPoint(1175, 85).click();
stop(TimerThenPlay);
clearTimeout(TimerThenPlay);
return;
},500)
};

Why are parameters not sent to a function in setInterval() all the time?

I have a page that automatically refreshes content via Ajax. I want this to be subtle so I do not want to display my loading gif during automatic page refreshed. So I did something like this with my getPosts function (unnecessary code cut out for succinctness)
function getPosts(image)
{
//loading icon while getPosts
if (image)
{
$("#postcontainer").bind("ajaxStart", function(){
$(this).html("<center><img src='ajax-loader.gif' /></center>");
});
} //... ajax call, etc. don't worry about syntax errors, they aren't in real code
I know the center tag is deprecated, just a shameless shortcut.
And then I will set the interval like setInterval(function() { getPosts(false); }, 10000);
Therefore my automated calls will not trigger the image to display
All my manual refreshes will then call it like this getPosts(true);
You can (probably) see the bug in action at my personal site
The problem is, the setInterval function seems to use the image bool from the latest function call. So it does not display the image at first during automated calls, but after I click a manual refresh, it starts showing the image during each call.
How can I combat this?
Thanks for anyone who views/posts this topic! I hope this question becomes a good reference to others.
The problem is that once you've bound your "ajaxStart" handler to the container it will execute on every ajax call for that container. That is, the first time you call it with getPosts(true) it will create the binding. The next time you call it with getPosts(false) it doesn't go down that if path but the binding still exists so when you do your ajax call the handler still executes - and the handler doesn't doesn't have any conditional logic. (Actually, I believe you'll end up with multiple bindings on the "ajaxStart" event, one created every time you call getPosts(true), but they're probably not noticable since they all just do the same thing overwriting the same html.)
Why not do something like this:
function getPosts(image) {
if (image) {
$("#postcontainer").html("<center><img src='ajax-loader.gif' /></center>");
}
// Actual ajax call here
}
setInterval(function() { getPosts(false); }, 10000);
Because after the first manual refresh you have attached a event handler "ajaxstart" which is to show the image when a ajax call starts. Now this event handler is there even in case you call the function with image = false. It will get triggered on all ajax calls.
What you need to do is something like:
$("#postcontainer").bind("ajaxStart", function(){
$(this).html("<center><img src='ajax-loader.gif' /></center>")
//Remove event handler
$(this).unbind("ajaxStart");
});

Problem with Jquery, setInterval inside a Facebook iframe

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

Changing visibility does not immediately hide iFrame

I have a page that on a certain action makes an iframe visible and fills the iframe with some HTML (say for example a multi-select box and an ok button).
The OK button on the iframe has the onClick method defined kinda like this:
onClick="parent.hideIFrame();parent.processMultiSelectBox();"
When User clicks OK on the iframe (presumably after playing with the multi-select box), I'd like the iFrame to disappear immediately and then the selected values in the multi-select box can be processed. But this is not what's happening. The iFrame remains visible during the time the other function runs and disappears only after the second function finishes.
The hideIFrame function is pretty straightforward:
function hideIFrame() {
frmObj = document.all.iFrameID;
if(frmObj) {
frmObj.style.visibility = "hidden";
}
}
I've paraphrased the above function for clarity (removed some indicator variable assignments etc.)
The second function actually loops on all the options in the multi-select object and does stuff with it. This takes about a half a second and only after that is done, does my iFrame disappear. It is a little bothersome to see it linger for half a second when I click ok.
My question is whether there is some way I can make the darn thing disappear faster. Speaking in "classical C" lingo, is there a "flush" for the change in visibility to happen immediately?
I did notice that if I put an "alert" as the first line in my second function, the iframe disappears immediately but now it is the OK on the alert box that lingers for the time it takes the second function to finish.
Thanks.
EDIT: Based on DDaviesBrackett's answer, this is what I ended up doing:
The onclick in the iframe changed to:
onClick="parent.hideAndProcessMultiSelectBox(parm1, parm2);"
The hideAndProcessMultiSelectBox function was defined as:
function hideAndProcessMultiSelectBox( parm1, parm2 ) {
hideIFrame();
setTimeout( function() { processMultiSelectBox( parm1, parm2 ); }, 0 );
}
Voila.. no delay..
You've gotten to the root of your problem already; document reflow doesn't happen until the current JS thread is done (so as not to repaint lots of times during JS execution). You need to return control to the browser before doing your expensive processing.
The simplest way to achieve that, though it doesn't make for obvious code in the slightest, is to call processMultiSelectBox in a setTimeout with a delay of 0:
onClick="parent.hideIFrame();parent.setTimeout(parent.processMultiSelectBox,0);"
If you need to pass parameters to the thing you're setting a timeout on, you have two options: set a timeout on a string that evals to Javascript (bad, bad, very bad, horrible) or define an anonymous function that calls the one you're interested in:
onClick="parent.hideIFrame();parent.setTimeout(function(){parent.processMultiSelectBox(foo, bar, 'baz');},0);"
RSolberg's response may also help, though there's a difference between visibility:hidden and display:none.

Categories