setTimeOut function not working as expected - javascript

I am having a hard time with setTimeOut function .Let me show the code first.
Here is my code :-
function submitform(loginUrl, username, password) {
try {
loc = new String(window.location);
document.forms.frm_login.action = junctionUrl;
document.forms.frm_login.username.value = username;
document.forms.frm_login.password.value = password;
document.forms.frm_login.submit();
setTimeout(gotoHomePage,4000);
}
catch (e) {
alert(e.message +"submit form");
}
}
function gotoHomePage()
{
alert("test");
var url = "test.aspx";
window.location=url;
}
But here the gotoHomePage function is not at all triggered after the specified
4 seconds.
What i am doing wrong here.Please suggest .
Any help will be appreciated.
Thanks

form submission is redirecting to the result page unloading the current page. So, the timer doesn't tick.
Use ajax or set target of the form to iframe. This way, the current page doesn't unload and so timer ticks executing your timeout function.
<form target="form_output">
<!-- other inputs -->
</form>
<iframe name="form_output"></iframe>

Related

location.href refreshes instead of redirecting

I'm making a javascript game and once the user finished the game, the user will enter their initials and hit submit. Once they hit submit, it'll redirect them to a new page (end.html). I'm not sure if I've set up my click event incorrectly or I'm using the wrong location.href. But, when I hit the submit button, it brings the user back to the start screen(index.html), instead of the end (highscore) page.
The script tag is located on the bottom of the HTML pages, tags are correctly named. I tried the DOMContentLoaded function and that didn't seem to work. If I need to provide more of my code, please let me know.
here's the js snippet
submitScore.addEventListener("click", function () {
var initials = document.getElementById("initials").value;
// calling highscore page function
endPage(initials, time);
});
function endPage(inits, scores) {
var userData = {
inits: inits,
scores: scores
};
highscores.push(userData);
localStorage.setItem("userData", JSON.stringify(highscores));
location.href = "end.html"
}
I personally have never used location.assign - have you tried location.replace()?
submitScore.addEventListener("click", function () {
var initials = document.getElementById("initials").value;
// calling highscore page function
endPage(initials, time);
});
function endPage(inits, scores) {
var userData = {
inits: inits,
scores: scores
};
highscores.push(userData);
localStorage.setItem("userData", JSON.stringify(highscores));
location.replace(`${location.origin}/end.html`);
// get base url and append 'end.html'
}
EDIT [for others confused]: Actual bug was that the button was being submitted - bravo epascarello for this code:
submitScore.addEventListener("click", function (evt) {
evt.preventDefault(); // prevent default behaviour of event

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

Need to clear session and logout user after 30 sec or after close browser

code is in MVC and also every request are using ajax call so no change in url.
using below code i ll able to perform firt opration that logout user if user inactive of 30 sec. but not able to perform action when user logout.
<script>
$(function () {
$("body").on('click keypress', function () {
ResetThisSession();
});
});
var timeInSecondsAfterSessionOut = 30; // to change the session time out, change this value. Must be in seconds.
var secondTick = 0;
function ResetThisSession() {
secondTick = 0;
}
function StartThisSessionTimer() {
secondTick++;
console.log(secondTick);
if (secondTick > timeInSecondsAfterSessionOut) {
clearTimeout(tick);
window.location = '/Account/LogOff/0';
}
tick = setTimeout("StartThisSessionTimer()", 1000);
}
StartThisSessionTimer();
</script>
alse i tried the unload or beforeunload method of script but result not proper as expect.
need to logout user if user not perform any action on 30 sec or if user close browser.
thanks in advance.
as i see the var tick is local, and is defined in every tick, so the timeout is called every second:
function StartThisSessionTimer() {
secondTick++;
console.log(secondTick);
if (secondTick > timeInSecondsAfterSessionOut) {
clearTimeout(tick);
window.location = '/Account/LogOff/0';
}
tick = setTimeout("StartThisSessionTimer()", 1000);
}
Try to separate the initializiaton of the timeout, outside of the same scope of repeater of timeout.
tell us if is useful.
Tks

Javascript onUnload Show offer and redirect to offer page if stays on page [duplicate]

Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.

incrementing a value after each refresh in javascript

I'm developing a web application in asp.net c#, which has a URL like this...
http://localhost:1096/DisplayPop3Email.aspx?emailId=10
After a given time, I want to refresh the page, increasing the value of emailId. This is a repeating process that should happen after a certain amount of time has passed.
After the first refresh, the URL should now look like this...
http://localhost:1096/DisplayPop3Email.aspx?emailId=11
I have written a javascript function to refresh the page after a fixed time, but how can i increase the value of emailid after each refresh?
This is my Javascript code...
<script type="text/javascript">
var sURL = unescape(window.location.pathname);
function doLoad(){
setTimeout("refresh()", 2*15000 );
}
function refresh(){
window.location.href = sURL;
}
</script>
<script type="text/javascript">
function refresh() {
window.location.replace( sURL );
}
</script>
I call doload() from inside another Javascript function, as per below...
<script type="text/javascript">
function openNewWindow(spcd,cval) {
var tt = spcd;
var testarray=(spcd).split('#%#');
for(i=0;i<testarray.length-1;i++) {
var theurl=testarray[i];
if(theurl=="http://www.colbridge.com"){
popupWin = window.open(theurl,'_blank','menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0')
break;
}
}
receiveval(cval);
doLoad();
}
</script>
I call openNewWindow(spcd) inside my asp.net page_load event.
Could someone please help me to identify how to increment the counter after each refresh.
Call the function below:
function goToNextId() {
var id = 1 + parseInt(window.location.href.match(/emailId=(\d+)/)[1]);
window.location.href = window.location.href.replace(/emailId=(\d+)/, "emailId=" + id);
}

Categories