How to call or make the javascript function from the Application_Start of global.asax in asp.net mvc(C#) application?
-
What are you trying to achieve?Lazarus– Lazarus2009-10-21 11:39:00 +00:00Commented Oct 21, 2009 at 11:39
-
The javascript function gets the data to be shown to the User from database through jquery. The javascript function will be executed periodically using setTimeout. I need to call this javascript function only once (not in $(document).ready), so that the setTimeout will take care of calling it again periodicallyPrasad– Prasad2009-10-21 11:43:38 +00:00Commented Oct 21, 2009 at 11:43
-
1Whats wrong with calling SetTimeout in $(document).ready ?LiamB– LiamB2009-10-21 11:44:29 +00:00Commented Oct 21, 2009 at 11:44
-
its gets reset when i move from first to second page.Prasad– Prasad2009-10-21 11:48:45 +00:00Commented Oct 21, 2009 at 11:48
-
@Prasad - that's standard behaviourRuss Cam– Russ Cam2009-10-21 12:11:05 +00:00Commented Oct 21, 2009 at 12:11
4 Answers
You can remember the last "invoked" time in Session or cookies (which is easier for javascript but worse for performance/etc) and then
function check() {
// or var lasttime = <%= Session["lasttime"] %>;
if (now - $.cookie("lasttime") > timeout)
{
$.cookie("lasttime", now);
performAction();
}
window.setTimeout(check, 1000);
}
You can call time function once from $(document).ready().
But note that it may take browser several seconds to render page, or it may bump into 404 or other errors and page will be inactive... javascript is not a reliable way to do scheduled actions.
Another way is to have your timer on server. JavaScript function like above will just ask for it from time to time, passing user ID or something like that. This will prevent timer reset during page reload. But you'll have to do request too often. So the best solution would be to combine two techniques:
- Run timer on server
- When page is renders, set var inited = false;
- Run function above but like this: if (!inited) timer = $.getJSON("/timer?uid=x"); and when you have the precise current timer you can continue with JavaScript only, without server requests.
3 Comments
"The javascript function gets the data to be shown to the User from database through jquery. The javascript function will be executed periodically using setTimeout"
This wouldnt be the place to do it.
Have you thought about using your masterpage?
4 Comments
Since JavaScript executes on client side and global.asax executes on server side. You cannot do that.