Sunday, September 19, 2010

Timer in javascript

With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events.

It's very easy to time events in JavaScript. The two key methods that are used are:

* setTimeout() - executes a code some time in the future
* clearTimeout() - cancels the setTimeout()

Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object.
The setTimeout() Method
Syntax
var t=setTimeout("javascript statement",milliseconds);

The setTimeout() method returns a value - In the statement above, the value is stored in a variable called t. If you want to cancel this setTimeout(), you can refer to it using the variable name.

The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a statement like "alert('5 seconds!')" or a call to a function, like "alertMsg()".

The second parameter indicates how many milliseconds from now you want to execute the first parameter.

lets say I wanted to start download a file after 5 seconds of loading my web page.
for that i created below function which i using javascript timer:


write it in script tag in .aspx file:
function startdown() {
var url = "<%= siteurl %>";
setTimeout("window.location.href='" + url + "';", 5000);
}

in .cs file write below code:
protected void Page_LoadComplete(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "downloadnewwin", "startdown();", true);

}

you can use this timer for calling various javascript function or for any other activity.

Solutions By:Rajesh Rolen

Share This!


1 comment:

Anonymous said...

Hey! I know this is kinda off topic but I was wondering which
blog platform are you using for this site? I'm getting fed
up of Wordpress because I've had issues with hackers
and I'm looking at options for another platform.

I would be great if you could point me in the direction of a good platform.

Powered By Blogger · Designed By Seo Blogger Templates