$(document).ready(function () {
function EndSession() {
window.close();
};
setTimeout("EndSession()", 10000);
});
Shown above is the code in a child page opened using window.open().
The problem is after ten seconds when it tries to call EndSession, it throws an error
"Microsoft JScript runtime error: 'EndSession' is undefined"
What is going on here?
Maybe the problem of the old way "string" is that it was looking for the method in the global scope, while the method was defined inside the function used for jQuery ready.
We can explicitly pass the function we really want to, if we have a proper reference to it.
Let's try:
$(document).ready(function () {
var endSession = function() {
window.close();
};
setTimeout(endSession, 10000);
});
Although I haven't tried it, maybe even this will work:
$(document).ready(function () {
setTimeout(window.close, 10000);
});
I'm not sure if you need the jQuery ready at all too, unless you intentionally want to start counting time after the document is fully loaded (which I'd expect to be very quick for a pop-up that closes soon).
When the timeout event triggers, the code you specified is run in the global namespace.
Your code is "EndSession()", so the browser tries to find a global function with the name EndSession. There is no such function, because you defined EndSession() inside an anonymous function that you passed to $(document).ready().
So, defining EndSession as global will suffice.
function EndSession() {
window.close();
};
$(document).ready(function () {
setTimeout("EndSession()", 10000);
});
Also, functions that are not constructors should, by convention, start with lowercase letter ;)
that should be like this,
setTimeout(EndSession, 10000);
DEMO
Related
I have a similar question before, my question was about how to access all the JavaScript functions in the web browser console even if they were within window.onload = function() {// code and functions} , but this time I want to do the same thing with jQuery:
$(document).ready(function() {
// I want to access all the functions that are here in the web console
})
You can use the same syntax as in your previous question. Simply assign the function to the window.
The following example illustrates what I mean. Note that you do not need the setTimeout(), this is just for this example here to auto-execute the your_function() when it is defined.
$(document).ready(function() {
window.your_function = function(){
console.log("your function");
};
your_function();
});
// setTimeout() is needed because the $.ready() function was not executed when
// this code block is reached, the function(){your_function();} is needed because
// the your_function() is not defined when the code is reached
setTimeout(function(){
your_function();
}, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Note 2: I suggenst not to define global functions in the $(document).ready() if there is not a good reason for it. You can define the functions outside and then call them in the $(document).ready().
I am accessing few methods written in another js file. So i'm accessing them like this:
file1:
function minit() {
this.addval = function(val1, val2) {
return val1 + val2;
}
function autoexecute(d) {
//do something here//
//raise event//
}
};
file2:
var con = new minit();
var result = con.addval(2, 3);
/*
con.autoexecute(function(d) { //Wanna do something like this
alert(d);
});
*/
Above things are working as expected, getting result..
Now, Suppose autoexecute(d) method is invoking automatically after a time interval. How can i know if the method is executed ?
So that, I want to create an event(in file2) of autoexecute(d)(in file1).
UPDATE:
I hope this example will help you to understand the issue..
company.js //this is the main file which will be used as a reference in ui.html
function hello(personname) { //this method will invoke automatically after 1 minute..
}
ui.html
<script src="company.js"></script>
<script>
$(document).ready(function() {
function bye(personame) { //this method will be called automatically if hello method invoked.... personame is the argument passed from hello method//
alert("comany.js -> hello function is executed");
}
});
</script>
You can only do this if the functions have the same scope (global scope is the best case scenario). If the autoexecute function has local scope then you cannot to do it.
In essence, override the original function like this...
// keep a reference to the original function
var _autoexecute = autoexecute;
// override the original function with your new one
function autoexecute(d) {
alert("before autoexecute"); // fired before the original autoexecute
_autoexecute(d); // call the original autoexecute function
alert("after autoexecute"); // fired after the original autoexecute
}
Now, whenever autotexecute is called it will call your new function which can handle both before and after events, as well as calling the original function. Just remove the (horrible) alerts and replace with event handlers as required.
To my knowledge, and someone should correct me if I am wrong, there is no way (at least without some library) to detect a function being fired in javascript. Function executions do not fire an event that other functions can 'handle' in that that sense.
In your example you wanted a function to automatically fire after the other function has fired, all you need to do is call the function you want to fire at the end of the one that was "fired" in the first place. Confusing but hope this helps.
function handler(){
alert("main function was fired!");
}
function main(){
//Code of main goes here and then at the end just add:
handler();
}
Now when your "main" has finished its work it will call upon the handler function.
Regardless of where you define the handler function, which can be a different file or same file, so long as it is reachable from within the main's scope, it will be fired at the end of it. It can even be declared after main has been declared, so long as it is declared before main is fired.
There's a little something about scope I just keep getting confused about:
this.init = function(){
var t = this;
setTimeout(function(){
// why is t still available here?
t.initgame();
// but not this?
this.initgame();
}, 500);
}
this.initgame = function() {
// yada yada
}
I get that inside an anonymous function, scope is different that outside of it.
But why, in the above example, is the variable "t" available inside the timeout function, while "this" is not working?
The problem is that setTimeout is called with window as scope.
Using a dedicated variable to store this (t) is a perfectly valid and usual solution.
On modern browsers, bind is sometimes convenient :
setTimeout((function(){
// use this
}).bind(this), 500);
When the anonymous function runs, it is no longer running as a member function of init, but rather a top-level function of window. As a result, this.initgame() has no meaning.
For example, running console.log(this) inside the timeout function returns as follows:
Window {top: Window, window: Window, location: Location, external:...
When you use var t = this, you assign reference to the current object, which works.
Say I add to First.js:
$(document).ready(
function () {
dosomething A
});
function () {
dosomething C
});
});
and to Second.js:
$(document).ready(
function () {
dosomething B
});
});
will all 3 functions be executed after DOM is ready?
What will be the case when I register
to First.js:
$(document).ready(
A = function () {
dosomething A
});
C = function () {
dosomething C
});
});
to Second.js:
$(document).ready(
A = function () {
dosomething A
});
});
The later will override the first?
TIA
Your first example is invalid syntax. It will cause the javascript interpreter to throw an exception. You need to pass one and only one function to $(document).ready(fn). You can include multiple function calls inside the one function, but you can only pass one function to .ready().
Your second example is also a syntax error - an extra });. If that is removed, it will work and execute that one function.
Your third example in both first.js and second.js is also a syntax error. You can't put arbitrary javascript as the parameter to .ready(). It must be one function reference with proper syntax.
Now, what you may have been trying to ask if you actually provided legal syntax in your examples is that all functions you pass to .ready(fn) will be executed when the document is ready. jQuery keeps an array of all functions that have been passed and executes them all when the document becomes ready. The jQuery documentation for .ready() does not specify the calling order if .ready() has been called multiple times with multiple functions, though one could examine the source code and see what the order is likely to be.
"will all 3 functions be executed after DOM is ready?"
Yes. Each time you bind something to be executed at DomReady, jQuery will queue the function in an internal array, then execute them in the same order as they where "inserted".
The later will override the first?
Yes it will, unless you put var before the definition. JavaScript will put A in the window scope, so the next definition will override the first.
function() {
var A = 0; // this will only exist within the function
}
function() {
A = 1; // this will be added to the "global" scope (window).
}
The later will override the first?
No, you can assign multiple functions to individual events.
I'm assuming your syntax errors were unintentional. The way they are written, NO code is executed.
Yes, you can bind the same event several times without problems.
Yes, the second code will replace the value set by the first code.
I have this code:
$(document).ready(function(){
var callPage = function(){
$.post('/pageToCall.php');
};
setInterval('callPage()', 60000);
});
and it gives me the error ReferenceError: Can't find variable: callPage. Why?
Try setInterval(callPage, 60000);.
If you pass a string to setInterval, then this string is evaluated in global scope. The problem is that callPage is local to the ready callback, it is not global.
There is hardly ever a reason to pass a string to setInterval (setTimeout). Always pass a function (to avoid exactly this kind of errors).
I suspect it's because callPage is a variable scoped to the anonymous function you're creating in the document.ready event. If you move the callPage definition outside that, does it work?
function callPage()
{
$.post('/pageToCall.php');
};
$(document).ready(function()
{
setInterval('callPage()', 60000);
});
It happens because callPage's scope is the anonymous function