Window, Location, and Navigator Objects
References
- W3Schools JavaScript Window Object
- W3Schools JavaScript Location Object
- W3Schools JavaScript Navigator Object
- W3Schools JavaScript setTimeout() Method
- W3Schools JavaScript setInterval() Method
The Browser Object Model
If you want to control or affect the browser window itself or the Web page (document) that the browser is displaying, you use the browser object model to do so. The browser object model (bom) (sometimes known as the document object model, or dom) is a hierarchy of objects. Each of the objects in the bom gives you, the JavaScript programmer, access to properties and methods that allow you to manipulate various aspects of the Web page or the browser itself.
The objects in the bom are automatically created whenever a document is loaded (displayed) in the browser. You do not need to create the objects in the bom.
Some of the objects in the bom are:
-
window
-
document
-
forms[ ]
- elements[ ]
- plugins[ ]
- applets[ ]
- anchors[ ]
- areas[ ]
- images[ ]
- links[ ]
- layers[ ]
- write( )
-
forms[ ]
- frames[ ]
-
location
- href
- search
- assign( )
- replace( )
-
history[ ]
- back( )
- forward( )
- go( )
-
navigator
- mimeTypes[ ]
- plugins[ ]
- appName
- appVersion
- alert( )
- confirm( )
- prompt( )
- open( )
- close( )
- setInterval( ) and clearInterval( )
- setTimeout( ) and clearTimeout( )
- self
-
document
- I have represented the hierarchy with bulleted lists.
- Some of the objects are actually arrays.
- The distinctions among "object", "property", and "method" get a bit fuzzy here. Notice that the location property is listed here as an object. Internally, JavaScript makes very little distinction.
The window object represents the Web browser window or an individual frame within a window.
The document object represents the HTML document that the browser is displaying.
The images[ ] object, as an example, is an array of objects, each element of which represents an <img> tag in the document.
In order for you to refer to an object in your JavaScript code, you must refer to the object's ancestors (the objects "above" it in the hierarchy), separating the names of the ancestor objects from one another with a period. For example, if you have an <img> tag in your document, you can refer to the src property of the object (for the first image in the page) in this way:
document.images[0].src(assuming that the image is the first image in the document).
As another example, if you want to refer to the text value that is in a text input field in a form, you can refer to it like this:
document.forms[0].elements[0].value(assuming that it is the first element in the first form in the document).
I hope you noticed that I left out a reference to the window object in the above two samples. In most cases, especially when you are using the document object, you can leave out the reference to the window object and the browser will assume that you are referring to the window object as the top-level object in the hierarchy.
Technically, in many situations you can also leave out the reference to the document object. But it is not considered good programming practice to do so. You should always include the reference to the document object.
If you ever see code like this in a JavaScript program:
self.alert("Hey!");
you should know that the self keyword refers to the
window object. So the above code could also be written as
window.alert("Hey!");
or even
alert("Hey!");
The Window Object
As I said above, the window object represents the Web browser window or an individual frame within a window.
Some of the properties in the window object are:
| Property | Description |
|---|---|
| document | A reference to the document object |
| frames[ ] | An array that lists the frame objects in the window |
| history[ ] | A reference to the history object, which is also an array of sites (URLs) previously visited in the current browser. |
| location | A reference to the location object |
| navigator | A reference to the navigator object |
| opener | A read/write property that refers to the window object that called open( ) to create this window. |
| parent | A read/write property that refers to the window object that contains the current window. If the current window is a top-level window (meaning: not in a frameset), the parent property refers to the current window itself. But if the current window is in a frame, parent refers to the window or frame that contains the current window. |
| status | A read/write string that specifies the contents of the status bar of the browser window |
| top | In a framed page, refers to the topmost window object that contains the current frame. In the top-most window itself, or if there is no frameset involved, top refers to the current window. |
| window | A self-reference to the window object. |
Some of the methods in the window object are:
| Method | Description |
|---|---|
| alert( ) | Displays a message dialog box with an OK button |
| blur( ) | Removes focus from the window |
| close( ) | Closes the window |
| confirm( ) | Displays a message dialog box with an OK and a Cancel button |
| focus( ) | Makes a window the active window |
| open( ) | Opens a new window (meaning that it opens a new instance of the browser) |
| prompt( ) | Displays a message dialog box with an input text field |
| setInterval( ) and clearInterval( ) | Instructs JavaScript to repeatedly run some code after a specified number of milliseconds have elapsed. Clears the interval timer. |
| setTimeout( ) and clearTimeout( ) | Runs some code once after a specified number of milliseconds have elapsed. Clears the timeout timer. |
Opening Windows
If you need to display a page in a new browser window, you can do it with the window.open( ) method. When you open a new window with this method, a new window object is created, which you can use to communicate between the original window and the new one.
(But keep in mind that in many situations, it is also possible to use the standard HTML <a href="..." target="_blank"> tag to open a new window. JavaScript gives you options that the <a> tag does not give you, though, so read on!)
The syntax for the window.open( ) object is shown below:
window.open(URL, Name, Features, Replace);where
- URL is a string that tells JavaScript what page or site to display in the new window.
- Name is a string that assigns a value to the name property of the new window object.
- Features is a comma-delimited string that tells JavaScript what features the new browser window will have, such as whether it will have a status bar, navigation bar, etc.
-
Replace is an optional value which specifies
whether the URL creates a new entry or replaces the current
entry in the browser's history list. The following values are supported:
true - URL replaces the current document in the history list false - URL creates a new entry in the history list
Technically, you can include all or none of the three arguments to the open( ) method. I recommend that you include all of these arguments, even if they are empty strings.
The Name argument assigns a value to the name property of the new window. If you give this argument a string value that is not one of the "magic" values (see below), you can use this name as the target attribute of a hypertext link to tell the link to display the linked-to page in the named window.
The possible values of this Name argument are: (The first four values are the "magic" values that I mentioned above.)
- _blank - URL is loaded into a new window. This is the default.
- _parent - URL is loaded into the parent frame of a frameset.
- _self - URL replaces the current page.
- _top - URL replaces any framesets that may be loaded.
- name - The name of the window
Here is some sample code that shows how this method can be used:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Opening a Window</title>
<script type="text/javascript">
/* <![CDATA[ */
var newWindow;
function openWindow()
{
newWindow = window.open("http://www.nasa.gov");
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<a href="#" onclick="openWindow(); return false;">
Visit the NASA home page.
</a>
</div>
</body>
</html>
You can see this code running here.
Please note these points about the above code:
- The href attribute in the <a> tag has a value of "#". This value fools the browser into looking for a non-existent anchor while the browser runs our onclick event handler code.
- The event handler calls a custom function to open a new window.
- The event handler also returns false to the browser. This return value instructs the browser to abandon its search for the non-existent anchor.
You can use the Features (third) argument of the open( )
method to customize how the new browser window appears. Here is a
list of some of the common options you can use in this third
argument:
| IE Feature | Firefox Feature | Description | Possible Values | Default Value |
|---|---|---|---|---|
| channelmode | Whether or not to display the window in theater mode. Default is no. IE only. | yes or no | no | |
| directories | Whether or not to add directory buttons. Default is yes. IE only. | yes or no | yes | |
| fullscreen | Whether or not to display the browser in full-screen mode. Default is no. A window in full-screen mode must also be in theater mode. IE only. | yes or no | no | |
| height | height | The height of the window. Min. value is 100. | Height in pixels | Minimum value is 100. |
| left | left | Sets the position of the left edge of the new window from the left edge of the screen | Left position in pixels | (last closed browser position) |
| location | location | Whether or not to display the address field. Default is yes. | yes or no | yes |
| menubar | menubar | Whether or not to display the menu bar. Default is yes. | yes or no | yes |
| resizable | resizable | Whether or not the window is resizable. Default is yes. | yes or no | yes |
| scrollbars | scrollbars | Whether or not to display scroll bars. Default is yes. | yes or no | yes |
| status | status | Whether or not to add a status bar. Default is yes. | yes or no | yes |
| titlebar | titlebar | Whether or not to display the title bar. Ignored unless the calling application is an HTML Application or a trusted dialog box. Default is yes. | yes or no | yes |
| toolbar | toolbar | Whether or not to display the browser toolbar. Default is yes. | yes or no | yes |
| top | The top position of the window. | Top position in pixels | (last closed browser position) | |
| width | width | The width of the window. Min. value is 100. | Width in pixels | Minimum value is 100. |
If you exclude the Features argument, or you make it an empty string, all of the standard/default features will be included in the new window. Actually, in practice, the new window will probably have the features of the most recently closed browser window on that machine, depending on the operating system.
However, and this is important, if you include the Features (third) argument in the open( ) method, only those features that you specify will be included in the new window.
Following is some sample code that shows how to use some of the Features options:
Here is the code that is in the page openWindow2.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Opening a Window</title>
<script type="text/javascript">
/* <![CDATA[ */
var newWindow;
function openWindow()
{
newWindow = window.open("directions.html",
"directions",
"height=300,width=700,left=50,top=50");
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<a href="#" onclick="openWindow(); return false;">
View some directions to my place.
</a>
</div>
</body>
</html>
Here is the code that is in the page directions.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Directions</title>
<style type="text/css">
body {background-color: #FFFFCC;"}
</style>
</head>
<body>
<div id="mainDiv">
<h3>Directions to My Place</h3>
<ol>
<li>Turn left at Elm St.</li>
<li>Turn right at Main St.</li>
<li>Pull into the parking garage at 123 Main St.</li>
</ol>
<button onclick="window.close();">Close</button>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code:
- The new window has no "interface" features, such as a menu bar, toolbars, or scroll bars; because we only specified the left, top, width, and height options.
- For the same reason, the window is not even resizable.
- For compatibility with some browsers, you should not include any spaces in the Features string.
- The document directions.html has a <button>...</button> tag in it, which uses an onclick event handler to close the window. Notice the use of the window.close() method.
Window Object Reference
If you want to do any manipulation of the new window that you have opened, you will need to save the new window object's reference in a variable. You can then use the variable as the object reference to properties and methods in the new window.
Please Note: When you open the sample pages given in this section, you might see some warnings or errors about cross-site scripting, depending on your browser.
Some reference sites say that you can possibly get around these errors or warnings by adding a meta tag to your page's <head> section.
If you choose to try this <meta> tag, it will probably look something like this:
<meta http-equiv="Access-Control-Allow-Origin" content="*">
Below are the sample pages.
Window Object Reference Sample 1
The first set of code opens
another window. The second set of code is the document that is
opened by the first set.
Here is the first set of code, which opens the second window. This
is WindowOpen4.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Saving Window Object Reference</title>
<script type="text/javascript">
/* <![CDATA[ */
var newWindow = null;
function openNewWindow()
{
newWindow = window.open("NewWindow.html", "MyWindow", "width=700,height=200");
}
function focusNewWindow()
{
if (newWindow != null)
{
newWindow.focus();
}
else
{
alert("There is no window to focus on!");
}
}
function closeNewWindow()
{
if (newWindow != null)
{
newWindow.close();
newWindow = null;
}
else
{
alert("There is no window to close!");
}
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<a href="#" onclick="openNewWindow(); return false;">Open a Window</a>
<br/>
<br/>
<a href="#" onclick="focusNewWindow(); return false;">Focus on the New Window</a>
<br/>
<br/>
<a href="#" onclick="closeNewWindow(); return false;">Close the New Window</a>
</div>
</body>
</html>
Here is the second set of code, which is the document (window) opened
by the first set. This is NewWindow.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>A New Window</title>
<script type="text/javascript">
/* <![CDATA[ */
function windowClose()
{
window.opener.newWindow = null;
self.close();
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<h3>This is a new window!</h3>
<a href="#" onclick="windowClose(); return false;">Close</a>
</div>
</body>
</html>
You can see the above sets of code running here. Please note these points about the above code:
- The variable newWindow is a global variable.
- The value null is assigned to the variable newWindow when it is created, and after the window is closed, so we can test whether the window is open or not in the focus( ) and close( ) code.
- In the three links at the bottom of the first set of code, the href attribute is "#" so the browser goes on a wild-goose chase for a non-existent anchor. This tactic allows us to handle the onclick event while the browser is looking for the non-existent anchor.
- Also in the three links at the bottom of the first set of code, the statement return false; tells the browser to stop trying to find the non-existent anchor. But by the time return false; is run, the browser will have handled the onclick event.
- In the second set of code, window.opener refers to the window that opened the current (second) window, and it allows us to change the value of the variable newWindow that is in the first window. This is JavaScript at its coolest! We assign the variable a null value so the first set of code continues to consistently detect a non-existent (or closed) second window.
Window Object Reference Sample 2
A second version of the "window object reference" sample code is below. In this version, there are two main differences:
- The main window, openWindow6.html, has an unload event handler in the <body> tag.
- The second window, NewWindow3.html, has a global variable openerWindow which it uses to detect whether or not the main window is still open. This feat of magic is accomplished by the code in the unload event handler function which is called from the main window's <body> tag.
Here is the second version of the main window, which opens the second window. This is openWindow6.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Saving Window Object Reference</title>
<script type="text/javascript">
/* <![CDATA[ */
var newWindow = null;
function openNewWindow()
{
if (newWindow == null)
{
newWindow = window.open("NewWindow3.html", "MyWindow", "width=700,height=200");
}
else
{
alert("The window is already open, silly!");
}
}
function focusNewWindow()
{
if (newWindow != null)
{
newWindow.focus();
}
else
{
alert("There is no window to focus on!");
}
}
function closeNewWindow()
{
if (newWindow != null)
{
newWindow.close();
newWindow = null;
}
else
{
alert("There is no window to close!");
}
}
function setClosed()
{
if (newWindow != null)
{
// This is the variable in the second window:
newWindow.openerWindow = null;
}
}
/* ]]> */
</script>
</head>
<body onunload="setClosed();">
<div id="mainDiv">
<a href="#" onclick="openNewWindow(); return false;">Open a Window</a>
<br/>
<br/>
<a href="#" onclick="focusNewWindow(); return false;">Focus on the New Window</a>
<br/>
<br/>
<a href="#" onclick="closeNewWindow(); return false;">Close the New Window</a>
</div>
</body>
</html>
Here is the second version of the second window. This is NewWindow3.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>A New Window</title>
<script type="text/javascript">
/* <![CDATA[ */
var openerWindow = null; //Is initialized as the page loads
function windowClose()
{
//setClosed();
self.close();
}
function setOpenerStatus()
{
if (openerWindow != null)
{
// This is the status bar in the first (original) window:
window.opener.status = "Hello there!";
}
else
{
alert("My opener went away!");
}
}
function setClosed()
{
if (openerWindow != null)
{
// This is the variable in the first (original) window:
window.opener.newWindow = null;
}
else
{
alert("My opener went away!");
}
}
function setOpener()
{
// Replaces the null value when the page is fully loaded
openerWindow = window.opener;
}
/* ]]> */
</script>
</head>
<body onload="setOpener();" onunload="setClosed();">
<div id="mainDiv">
<h3>This is a new window!</h3>
<a href="#" onclick="windowClose(); return false;">Close</a>
<br/>
<br/>
<a href="#" onclick="setOpenerStatus(); return false;">Change the status of the opener</a>
</div>
</body>
</html>
You can see the second sample code running here.
The Location Object
The Location object contains information about the current URL, meaning information about the page that is currently displayed in the browser.
The Location object also allows you to display another Web page in place of the one that is currently open in the browser. And it allows you to redirect a Web page to another Web page.
In general, and in other words, the Location object contains properties and methods that you can use:
- to work with the document that is currently displayed in the browser, or
- to change which document is displayed in the browser.
Recall that in order to refer to a property or a method in an object, you must include the name of the object, followed by a period, and then the name of the property or method.
One of the interesting things about the Location object is that you can refer to it from either the window object or the document object. This means that
window.locationand
document.location
both refer to the same location object.
Or you may even just refer to this object as
location
But there is one situation in which you must refer to the location object as belonging to the window object: If you are changing the location properties of a window that you have opened with the window.open( ) method, you will need to refer to the location object as a member of the opened window object that you've saved the reference to. For instance, if you use code like this to open a window:
var newWindow;
newWindow = window.open('NextPage.html','nextPage','left=200,top=200,width=400,height=400');
you would use code like this to change the href property (see below) of the new window that is opened:
newWindow.location.href = "anotherWindow.html";
Here is a list of the properties in the location object:
| Property | Description |
|---|---|
| hash | A URL's anchor (the # sign and its value) |
| host | The host and domain name (or IP address) of a network host |
| hostname | The combination of the the host name and port properties |
| href | The full URL address of the currently-displayed document |
| pathname | The URL's path |
| port | The URL's port |
| protocol | The URL's protocol |
| search | The URL's search or query section (following the ? mark) |
Here is a list of the methods in the location object:
| Method | Description |
|---|---|
| assign( ) | Loads a new HTML document, and adds a new entry in the history list |
| reload( ) | Causes the currently-displayed page to reload |
| replace( ) | Replaces the currently-displayed page with another page, and also replaces the current page's entry in the history list |
Here, to satisfy your curiosity about what the location object's
properties look like, is a list of these properties for the current page:
And now here is one of the most important points about the Location object: You can change the href property to tell the browser to display another page, like the following example. This is page LocationHref.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Changing the href Property</title>
<script type="text/javascript">
/* <![CDATA[ */
function loadNewPage(newURL)
{
document.location.href = newURL;
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<a href="#" onclick="loadNewPage('http://w3schools.com'); return false;">
w3schools
</a>
<br/>
<br/>
<a href="#" onclick="loadNewPage('https://swiftpackageindex.com/swiftwasm/JavaScriptKit/0.22.2/documentation/javascriptkit'); return false;">
JavaScript Kit
</a>
</div>
</body>
</html>
You can see the above page running here.
Please note these points about the above code:
- I have used a single function to handle both onclick events.
- The parameter newURL is a string that is assigned to the href property. It must be a properly-formatted URL.
- I return false in the onclick event handlers in order to tell the browser to stop trying to find the fake href of the <a> tag, which is "#".
You can also use the assign( ) method of the location object to accomplish exactly the same thing as changing the href property. Here is some code that does the same thing as the previous example, but it uses the assign( ) method. This is page LocationAssign.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Using the Assign Method</title>
<script type="text/javascript">
/* <![CDATA[ */
function loadNewPage(newURL)
{
document.location.assign(newURL);
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<a href="#" onclick="loadNewPage('http://w3schools.com'); return false;">
w3schools
</a>
<br/>
<br/>
<a href="#" onclick="loadNewPage('https://swiftpackageindex.com/swiftwasm/JavaScriptKit/0.22.2/documentation/javascriptkit'); return false;">
JavaScript Kit
</a>
</div>
</body>
</html>
You can see the above page running here.
The reload( ) method is equivalent to the user's clicking the Reload or Refresh button on their browser. You can send a boolean argument to this method to tell the browser whether it should reload the page whether or not the page on the server has changed. So if you use code like this
location.reload(true);the page will reload from the server even if it has not changed. But if you use code like this
location.reload(false);or even
location.reload();the page will only reload from the server if it has changed.
The replace( ) method works similarly to the assign( ) method, but there is an important difference: The replace( ) method displays a new document, but it also replaces the previous document's entry in the browser's history list. In contrast, the assign( ) method or changing the href property add an entry to the browser's history list. See below for some details about the history object.
The Navigator Object
The navigator object is used to obtain information about the Web browser itself. This object is available in every browser, even though it originally got its name from Netscape Navigator.
Some of the properties in the navigator object are:
| Property | Description |
|---|---|
| appCodeName | The code name of the browser |
| appName | The name of the browser |
| appVersion | The version of the browser |
| platform | The operating system that the computer is using |
| userAgent | Browser, platform name, and compatibility information |
Here, to satisfy your curiosity about what the navigator object's
properties look like, is a list of these properties for the browser
you are using:
If you ever need to find out if browser cookies are enabled for
the user's browser,
one of the properties in the navigator object is:
| Property | Description |
|---|---|
| cookieEnabled | Contains true if cookies are enabled in the browser; contains false if not |
For the browser you are currently using, the return from this method is:
(I used the following code to display this value--)
<p> For the browser you are currently using, the return from this method is: <br><br> <b><script type="text/javascript"> /* <![CDATA[ */ document.write(navigator.cookieEnabled); /* ]]> */ </script></b> </p>
The following example page uses a lot of String-object functions, but it is a good example of somewhat useful coding, using the Navigator object. This is page Navigator.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>JavaScript Navigator Object</title>
<script type="text/javascript">
/* <![CDATA[ */
function showBrowserInfo()
{
/* Get the raw browser info: */
var theUserAgent = navigator.userAgent;
/* For ease of looping over the browsers, create some arrays: */
var browserArray = new Array("MSIE","Firefox","Chrome");
/* offsetArray is how far past the browser name the version info is */
var offsetArray = new Array(5,8);
/* lengthArray is how long the version info is */
var lengthArray = new Array(3,5);
var browserFound = false;
var namePos;
var browserName = "Unknown";
var versionInfo = "Not determined";
var browserInfo;
for (var i = 0; i < browserArray.length; i++)
{
namePos = theUserAgent.indexOf(browserArray[i]);
if (namePos >= 0)
{
browserFound = true;
versionInfo = theUserAgent.substr(namePos + offsetArray[i], lengthArray[i]);
browserName = browserArray[i];
/* If we found the browser, we don't need to loop any more: */
break;
}
}
browserInfo = browserName + " version " + versionInfo;
return (browserInfo);
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<h3>The browser being used is:
<script type="text/javascript">
/* <![CDATA[ */
document.write(showBrowserInfo());
/* ]]> */
</script>
</h3>
</div>
</body>
</html>
You can see the above page running in the browser here.
Please note the following points about the above page:
- The Navigator object's userAgent property is supplying the information about the browser which is displaying the page.
- There are three arrays in the page. They are created using the alternative method of specifying the elements of the array as arguments to the Array() function.
- The array browserArray is being used to determine for what browsers the code will look for version information. The other two arrays are being used to supply the arguments to the substr( ) method, for their respective browsers in the browserArray array.
Timeouts
You can tell JavaScript to run some code after a specified time period has elapsed, with the setTimeout( ) method. This method is contained in the window object, but you can refer to this method without explicitly referring to the window object. The code that is run after the time period has elapsed is run only once.
The syntax of setTimeout( ) is:
setTimeout("code", milliseconds);
where
"code"is the JavaScript code that you want to run after the time period has elapsed, and
millisecondsis the time period, in milliseconds. Five seconds, for instance, is 5000 milliseconds.
This method returns an identifier which can be used as the argument to the clearTimeout( ) method to cancel the timeout before it runs its associated code. But if you are going to use clearTimeout( ), you will need to save the identifier in a variable when you call setTimeout( ).
Here is some code that shows how you can use setTimeout( ) and clearTimeout( ). This is page SetTimeout.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>setTimeout and clearTimeout</title>
<script type="text/javascript">
/* <![CDATA[ */
var buttonNotPressed = setTimeout("alert('You forgot to press the button!')", 3000);
function buttonPressed()
{
clearTimeout(buttonNotPressed);
alert("You canceled the timeout code.");
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<form action="" method="post">
<input type="button" value="Press to Cancel the Timeout"
onclick="buttonPressed();" />
</form>
</div>
</body>
</html>
You can see the above code running here. Please note these points about the above code:
- The first line of JavaScript code runs when the page loads. It sets the timeout to 3 seconds and saves the timeout identifier in a global variable.
- The code that will run after the 3 seconds has elapsed is an alert( ) statement.
- If the user clicks the input button before the 3 seconds has elapsed, the timeout is canceled. The argument to the clearTimeout( ) method is the global variable that contains the timeout identifier.
Intervals
You can tell JavaScript to run some code repeatedly after a specified time interval with the setInterval( ) method. A related method, which clears the interval and its code, is clearInterval( ).
The syntax for setInterval( ) is similar to the syntax for setTimeout( ) and is shown below:
setInterval("code", milliseconds);
This method returns an identifier that can be saved in a
variable and then used as the argument to clearInterval( ). Here is some code that shows how setInterval( ) and clearInterval() can be used. This is page SetInterval.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>setInterval and clearInterval</title>
<script type="text/javascript">
/* <![CDATA[ */
var intervalID = setInterval("changeCounter();", 1000);
var counter = 0;
function changeCounter()
{
counter++;
document.getElementById("counterDiv").innerHTML = counter;
}
function buttonPressed()
{
clearInterval(intervalID);
document.getElementById("counterDiv").innerHTML = "";
alert("You canceled the counter update.");
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<form action="" method="post">
<input type="button" value="Press to Cancel the Counter Update"
onclick="buttonPressed();" />
</form>
<div id="counterDiv"></div>
</div>
</body>
</html>
You can see the above code running here. Please note these points about the above code:
- The variables intervalID and counter are global variables.
- The interval is set at 1 second when the page loads.
- Every 1 second, the status bar of the browser is updated with the new value of the counter variable.
- The clearInterval( ) method has one argument, which is the saved interval identifier.