Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 44

Enable JavaScript - Internet Explorer

In Internet Explorer 6/7 (download Internet Explorer), you can check to see if JavaScript is
enabled by navigating to the custom security settings that are somewhat buried (don't worry;
we'll help you find it).

1. Click on the Tools menu


2. Choose Internet Options... from the menu
3. Click the Security tab on the Internet Options pop up
4. Click the Custom Level... button to access your security settings
5. Scroll almost all the way down to the Scripting section
6. Select the Enable button for Active scripting
7. Click OK to finish the process
8. Click Yes when asked to confirm

Enable JavaScript - Firefox


In Firefox 2 (download Firefox) you can check to see if JavaScript is enabled by navigating to
the Content settings under Options.

1. Click on the Tools menu


2. Choose Options... from the menu
3. Click the Content tab in the Options pop up
4. Make sure that Enable JavaScript is checked
5. Click OK to finish the process

Enable JavaScript - Opera


In Opera (download Opera) you can check to see if JavaScript is enabled by navigating to the
Content settings under Preferences.

1. Click on the Tools menu


2. Choose Preferences... from the menu
3. Click the Advanced tab in the Preferences pop up
4. Select Content from the list of items on the left
5. Make sure that Enable JavaScript is checked
6. Click OK to finish the process

JavaScript Detection
These days, it's basically impossible to navigate the web without a JavaScript-enabled browser,
so checking whether or not a user has JavaScript enabled is not all that important. Chances are,
the only way it be disabled is if the company's IT staff has decided to disable JavaScript for some
reason. However, if you still want to be sure your users are JavaScript enabled, this script will
get it done.

The only sure fire way to separate users who don't have JavaScript from those who do is to use a
simple redirect script that will only work for those with JavaScript enabled. If a person's browser
does not have JavaScript enabled, the script will not run, and they will remain on the same page.

<html>
<body>
<script type="text/JavaScript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

An Example Head Script


Since we have already seen the kind of script that goes in the body, how about we write a script
that takes place when some event occurs? Let's have an alert show up when a user click on a
button.

HTML & JavaScript Code:


<html>
<head>
<script type="text/JavaScript">
<!--
function popup() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button"
onclick="popup()" value="popup">
</body>
</html>
Importing an External JavaScript File
Importing an external file is relatively painless. First, the file you are importing must be valid
JavaScript, and only JavaScript. Second, the file must have the file extension ".js". Lastly, you
must know the location of the file.

Let us assume we have a file "myjs.js" that contains a one line Hello World alert function. Also,
let us assume that the file is the same directory as the HTML file we are going to code up. To
import the file you would do the following in your HTML document.

File myjs.js Contents:


function popup() {
alert("Hello World")
}
HTML & JavaScript Code:
<html>
<head>
<script src="myjs.js">
</script>
</head>
<body>
<input type="button"
onclick="popup()" value="Click
Me!">
</body>
</html>

JavaScript Arithmetic Operator Chart


Operator English Example
+ Addition 2+4
- Subtraction 6-2
* Multiplication 5 * 3
/ Division 15 / 3
% Modulus 43 % 10

Modulus % may be a new operation to you, but it's just a special way of saying "finding the
remainder". When you perform a division like 15/3 you get 5, exactly. However, if you do 43/10
you get an answer with a decimal, 4.3. 10 goes into 40 four times and then there is a leftover.
This leftover is what is returned by the modulus operator. 43 % 10 would equal 3.

JavaScript Operator Example with Variables


Performing operations on variables that contain values is very common and easy to do. Below is
a simple script that performs all the basic arithmetic operations.
HTML & JavaScript Code:
<body>
<script type="text/JavaScript">
<!--
var two = 2
var ten = 10
var linebreak = "<br />"
document.write("two plus ten = ")
var result = two + ten
document.write(result)
document.write(linebreak)
document.write("ten * ten = ")
result = ten * ten
document.write(result)
document.write(linebreak)
document.write("ten / two = ")
result = ten / two
document.write(result)
//-->
</script>
</body>
Display:
two plus ten = 12
ten * ten = 100
ten / two = 5

JavaScript Using Variables


A variable's purpose is to store information so that it can be used later. A variable is a symbolic
name that represents some data that you set. To think of a variable name in real world terms,
picture that the name is a grocery bag and the data it represents are the groceries. The name
wraps up the data so you can move it around a lot easier, but the name is not the data!

A Variable Example
When using a variable for the first time it is not necessary to use "var" before the variable name,
but it is a good programming practice to make it crystal clear when a variable is being used for
the first time in the program. Here we are showing how the same variable can take on different
values throughout a script.
HTML & JavaScript Code:
<body>
<script type="text/JavaScript">
<!--
var linebreak = "<br />"
var my_var = "Hello World!"

document.write(my_var)
document.write(linebreak)
0
my_var = "I am learning JavaScript!"
document.write(my_var)
document.write(linebreak)

my_var = "Script is Finishing up..."


document.write(my_var)
//-->
</script>
</body>
Display:
Hello World!
I am learning JavaScript!
Script is Finishing up...

We made two variables in this example--one to hold the HTML for a line break and the other for
a dynamic variable that had a total of three different values throughout the script.

To assign a value to a variable, you use the equal sign (=) with the variable on the left and the
value to be assigned on the right. If you swap the order, your script will not work correctly! In
English, the JavaScript "myVar = 'Hello World!'" would be: myVar equals 'Hello World!'.

The first time we used a variable, we placed var in front to signify its first use. This is an easy
way to organize the variables in your code and see when they came into existence. In subsequent
assignments of the same variable, we did not need the var.
JavaScript Variable Naming Conventions
When choosing a variable name, you must first be sure that you do not use any of the JavaScript
reserved names Found Here. Another good practice is choosing variable names that are
descriptive of what the variable holds. If you have a variable that holds the size of a shoe, then
name it "shoe_size" to make your JavaScript more readable.

Finally, JavaScript variable names may not start with a numeral (0-9). These variable names
would be illegal: 7lucky, 99bottlesofbeer, and 3zacharm.

A good rule of thumb is to have your variable names start with a lowercase letter (a-z) and use
underscores to separate a name with multiple words (i.e. my_var, strong_man, happy_coder, etc).

What's a Function?
A function is a piece of code that sits dormant until it is referenced or called upon to do its
"function". In addition to controllable execution, functions are also a great time saver for doing
repetitive tasks.

Instead of having to type out the code every time you want something done, you can simply call
the function multiple times to get the same effect. This benefit is also known as "code
reusability".

Example Function in JavaScript


A function that does not execute when a page loads should be placed inside the head of your
HTML document. Creating a function is really quite easy. All you have to do is tell the browser
you're making a function, give the function a name, and then write the JavaScript like normal.
Below is the example alert function from the previous lesson.

HTML & JavaScript Code:


<html>
<head>
<script type="text/javascript">
<!--
function popup() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="popup()"
value="popup">
</body>
</html>
Display:

We first told the browser we were going to be using a function by typing "function". Next, we
gave our function a name, so that we could use it later. Since we are making a pop up alert, we
called our function "popup".

The curly braces "{,}" define the boundaries of our function code. All popup function code must
be contained within the curly braces.

Something that might be slightly confusing is that within our "popup" function, we use another
function called "alert," which brings up a popup box with the text that we supply it. It is perfectly
OK to use functions within functions, like we have done here. Furthermore, this is one of the
great things about using functions!

What we didn't talk about was how we got this function to execute when the button is clicked.
The click is called an event, and we will be talking about how to make functions execute from
various types of events in the next lesson

The building blocks of an interactive web page is the JavaScript event system. An event in
JavaScript is something that happens with or on the webpage. A few example of events:

 A mouse click
 The webpage loading
 Mousing over a hot spot on the webpage, also known as hovering
 Selecting an input box in an HTML form
 A keystroke

A Couple of Examples Using Events


JavaScript has predefined names that cover numerous events that can occur, including the ones
listed above. To capture an event and make something happen when that event occurs, you must
specify the event, the HTML element that will be waiting for the event, and the function(s) that
will be run when the event occurs.

We have used a JavaScript event in a previous lesson, where we had an alert popup when the
button was clicked. This was an "onclick" JavaScript event. We will do that same example again,
as well as the mouseover and mouseout events.

HTML & JavaScript Code:


<html>
<head>
<script type="text/javascript">
<!--
function popup(x,y) {
alert("Hello World")
return x+y;
}
Z=popup(10,20);

//-->
</script>
</head>
<body>

<input type="button" value="Click Me!"


onclick="popup()"><br />
<a href="#" onmouseover="" onMouseout=" ">
Hover Me!</a>
</body>
</html>
Display:

Hover Me!

With the button we used the event onClick event as our desired action and told it to call our
popup function that is defined in our header. To call a function you must give the function name
followed up with parenthesis "()".

Our mouseover and mouseout events were combined on one HTML element--a link. We wanted
to do nothing when someone put their mouse on the link, but when the mouse moves off the link
(onMouseout), we displayed a popup.

The HTML DOM Tree

When a web page is loaded, the browser creates an object model of the page.

The model is called the HTML DOM (Document Object Model).

The model is constructed as a tree of objects:


The HTML DOM Tree

Using the DOM, JavaScript can access all the elements of an HTML document.

Finding HTML Elements

Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are a couple of ways to do this:

 Finding HTML elements by id


 Finding HTML elements by tag name
 Finding HTML elements by class

Finding HTML Elements by Id

Often you will want to find HTML elements by using the element id. Use this DOM method:

var x=document.getElementById("id_name");

If the element is found, the method will return the element as an object (in x).

If the element is not found, x will contain null.


Changing HTML Content

The easiest way to modify the content of an HTML element is by using the innerHTML
property.

The following example changes the content of a <p> element:

<html>
<head>
<script>
function change(){
document.getElementById("p1").innerHTML="New text!";
}
</script>
</head>
<body>

<p id="p1">Hello World!</p>

</body>
</html>
Changing HTML Style

The following example changes the style of a <p> element:


<html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color="blue";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

JavaScript Functions

A function is a block of code that executes only when you tell it to execute.

It can be when an event occurs, like when a user clicks a button, or from a call within your script,
or from a call within another function.

Functions can be placed both in the <head> and in the <body> section of a document, just make
sure that the function exists, when the call is made.

How to Define a Function


Syntax
function functionname()
{
some code
}

The { and the } defines the start and end of the function.

Note: Do not forget about the importance of capitals in JavaScript! The word function must be
written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a
function with the exact same capitals as in the function name.
JavaScript Function Example

Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>

<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>

Try it yourself »

The function is executed when the user clicks the button.

You will learn more about JavaScript events in the JS Events chapter.

Calling a Function with Arguments

When you call a function, you can pass along some values to it, these values are called
arguments or parameters.

These arguments can be used inside the function.

You can send as many arguments as you like, separated by commas (,)

myFunction(argument1,argument2)

Declare the argument, as variables, when you declare the function:

function myFunction(var1,var2)
{
some code
}

The variables and the arguments must be in the expected order. The first variable is given the
value of the first passed argument etc.

Example
<button onclick="myFunction('Harry Potter','Wizard')">Try
it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

The function above will alert "Welcome Harry Potter, the Wizard" when the button is clicked.

The function is flexible, you can call the function using different arguments, and different
welcome messages will be given:

Example

<!DOCTYPE html>
<html>
<body>
<p>Click one of the buttons to call a function with
arguments</p>

<button onclick="myFunction('Harry Potter','Wizard')">Click


for Harry Potter</button>
<button onclick="myFunction('Bob','Builder')">Click for
Bob</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

</body>
</html>
The example above will alert "Welcome Harry Potter, the Wizard" or "Welcome Bob, the
Builder" depending on which button is clicked.

Functions With a Return Value

Sometimes you want your function to return a value back to where the call was made.

This is possible by using the return statement.

When using the return statement, the function will stop executing, and return the specified value.

Syntax
function myFunction()
{
var x=5;
return x;
}

The function above will return the value 5.

Note: It is not the entire JavaScript that will stop executing, only the function. JavaScript will
continue executing code, where the function-call was made from.

The function-call will be replaced with the returnvalue:

var myVar=myFunction();

The variable myVar holds the value 5, which is what the function "myFunction()" returns.

You can also use the returnvalue without storing it as a variable:

document.getElementById("demo").innerHTML=myFunction();

The innerHTML of the "demo" element will be 5, which is what the function "myFunction()"
returns.

You can make a returnvalue based on arguments passed into the function:

Example

Calculate the product of two numbers, and return the result:


function myFunction(a,b)
{
return a*b;
}

document.getElementById("demo").innerHTML=myFunction(4,3);

The innerHTML of the "demo" element will be:

12

The return statement is also used when you simply want to exit a function. The return value is
optional:

function myFunction(a,b)
{
if (a>b)
 {
  return;
 }
x=a+b
}
The function above will exit the function if a>b, and will not calculate the sum of a and b.

Everything" in JavaScript is an Object: a String, a Number, anArray, a Function....

In addition, JavaScript allows you to define your own objects.

JavaScript Objects

JavaScript has several built-in objects, like String, Date, Array, and more.

An object is just a special kind of data, with properties and methods.


Accessing Object Properties

Properties are the values associated with an object.

The syntax for accessing the property of an object is:

objectName.propertyName
This example uses the length property of the String object to find the length of a string:

var message="Hello World!";


var x=message.length;
The value of x, after execution of the code above will be:

12

Accessing Objects Methods

Methods are the actions that can be performed on objects.

You can call a method with the following syntax:

objectName.methodName()
This example uses the toUpperCase() method of the String object, to convert a text to uppercase:

var message="Hello world!";


var x=message.toUpperCase();
The value of x, after execution of the code above will be:

HELLO WORLD!
Creating JavaScript Objects

With JavaScript you can define and create your own objects.

There are 2 different ways to create a new object:

 1. Define and create a direct instance of an object.


 2. Use a function to define an object, then create new object instances.

Creating a Direct Instance

This example creates a new instance of an object, and adds four properties to it:

Example
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";

Alternative syntax (using object literals):

Example
personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

Math Object

The Math object allows you to perform mathematical tasks.


The Math object includes several mathematical constants and methods.

Syntax for using properties/methods of Math:

var x=Math.PI;
var y=Math.sqrt(16);
Note: Math is not a constructor. All properties and methods of Math can be called by using Math
as an object without creating it.

Mathematical Constants

JavaScript provides eight mathematical constants that can be accessed from the Math object.
These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2
log of E, and base-10 log of E.

You may reference these constants from your JavaScript like this:

Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

Mathematical Methods

In addition to the mathematical constants that can be accessed from the Math object there are
also several methods available.

The following example uses the round() method of the Math object to round a number to the
nearest integer:

document.write(Math.round(4.7));
The code above will result in the following output:

The following example uses the random() method of the Math object to return a random number
between 0 and 1:

document.write(Math.random());
The code above can result in the following output:

0.5339408550218532

The following example uses the floor() and random() methods of the Math object to return a
random number between 0 and 10:

document.write(Math.floor(Math.random()*11));

The code above can result in the following output:

10

Browser Detection

Almost everything in this tutorial works on all JavaScript-enabled browsers. However, there are
some things that just don't work on certain browsers - especially on older browsers.

Sometimes it can be useful to detect the visitor's browser, and then serve the appropriate
information.

The Navigator object contains information about the visitor's browser name, version, and more.

The Navigator Object

The Navigator object contains all information about the visitor's browser:

<!DOCTYPE html>

<html>

<body>

<div id="example"></div>
<script>

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";

txt+= "<p>Browser Name: " + navigator.appName + "</p>";

txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";

txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";

txt+= "<p>Platform: " + navigator.platform + "</p>";

txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";

document.getElementById("example").innerHTML=txt;

</script>

</body>

</html>

JavaScript Form Validation


JavaScript Form Validation

JavaScript can be used to validate data in HTML forms before sending off the content to a
server.

Form data that typically are checked by a JavaScript could be:

 has the user left required fields empty?


 has the user entered a valid e-mail address?
 has the user entered a valid date?
 has the user entered text in a numeric field?
Required Fields

The function below checks if a field has been left empty. If the field is blank, an alert box alerts a
message, the function returns false, and the form will not be submitted:

<!DOCTYPE html>

<html>

<head>

<script>

function validateForm()

var x=document.forms["myForm"]["fname"].value;

if (x==null || x=="")

alert("First name must be filled out");

return false;

</script>

</head>

<body>

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">

First name: <input type="text" name="fname">

<input type="submit" value="Submit">

</form>

</body>
</html>

E-mail Validation

The function below checks if the content has the general syntax of an email.

This means that the input data must contain an @ sign and at least one dot (.). Also, the @ must
not be the first character of the email address, and the last dot must be present after the @ sign,
and minimum 2 characters before the end:

<!DOCTYPE html>

<html>

<head>

<script>

function validateForm()

var x=document.forms["myForm"]["email"].value;

var atpos=x.indexOf("@");

var dotpos=x.lastIndexOf(".");

if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)

alert("Not a valid e-mail address");

return false;

</script>

</head>

<body>

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">


Email: <input type="text" name="email">

<input type="submit" value="Submit">

</form>

</body>

</html>

JavaScript RegExp Object


RegExp Object

A regular expression is an object that describes a pattern of characters.

Regular expressions are used to perform pattern-matching and "search-and-replace" functions on


text.

Syntax
var patt=new RegExp(pattern,modifiers);

or more simply:

var patt=/pattern/modifiers;

 pattern specifies the pattern of an expression


 modifiers specify if a search should be global, case-sensitive, etc.

Modifiers
Modifiers are used to perform case-insensitive and global searches:

Modifier Description
i Perform case-insensitive matching
Perform a global match (find all matches rather than stopping after the first
g
match)
m Perform multiline matching
<!DOCTYPE html>

<html>

<body>

<script>

var str = "Visit W3Schools";

var patt1 = /W3Schools/g;

document.write(str.match(patt1));

</script>

</body>

</html>

<!DOCTYPE html>

<html>

<body>

<script>

var str="Is this all there is?";

var patt1=/is/g;

document.write(str.match(patt1));
</script>

</body>

</html>

<!DOCTYPE html>

<html>

<body>

<script>

var str="Is this all there is?";

var patt1=/is/gi;

document.write(str.match(patt1));

</script>

</body>

</html>

Brackets are used to find a range of characters:

Expression Description
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
[A-z] Find any character from uppercase A to lowercase z
[adgk] Find any character in the given set
[^adgk] Find any character outside the given set
(red|blue|green) Find any of the alternatives specified
<!DOCTYPE html>
<html>
<body>

<script>
var str="Is tHis all there is?";
var patt1=/[a-h]/g;
document.write(str.match(patt1));
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<script>
var str="Is this all there is?";
var patt1=/[^a-h]/g;
document.write(str.match(patt1));
</script>

</body>
</html>

Metacharacters
Metacharacters are characters with a special meaning:

Metacharacter Description
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word
\B Find a match not at the beginning/end of a word
\0 Find a NUL character
\n Find a new line character
\f Find a form feed character
\r Find a carriage return character
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
\xdd Find the character specified by a hexadecimal number dd
Find the Unicode character specified by a hexadecimal number
\uxxxx
xxxx

<!DOCTYPE html>
<html>
<body>

<script>
var str="Give is 100";
var patt1=/\w/g;
document.write(str.match(patt1));
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<script>
var str="Give 100%!";
var patt1=/\W/g;
document.write(str.match(patt1));
</script>

</body>
</html>
Quantifiers
Quantifier Description
n+ Matches any string that contains at least one n
Matches any string that contains zero or more occurrences of
n*
n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
Matches any string that is not followed by a specific string n
?!n

<!DOCTYPE html>
<html>
<body>

<script>
var str="Hellooo World! Hello W3Schools!";
var patt1=/o+/g;
document.write(str.match(patt1));
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<script>
var str="Hellooo World! Hello W3Schools!";
var patt1=/lo*/g;
document.write(str.match(patt1));
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<script>
var str="1, 100 or 1000?";
var patt1= /10*/g;
document.write(str.match(patt1));
</script>

</body>
</html>

RegExp Object Properties


Property Description
global Specifies if the "g" modifier is set
ignoreCase Specifies if the "i" modifier is set
lastIndex The index at which to start the next match
multiline Specifies if the "m" modifier is set
source The text of the RegExp pattern

RegExp Object Methods


Method Description
compile() Compiles a regular expression
exec() Tests for a match in a string. Returns the first match
test() Tests for a match in a string. Returns true or false

JavaScript Timing Events


With JavaScript, it is possible to execute some code at specified time-intervals. This is called
timing events.

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

 setInterval() - executes a function, over and over again, at specified time intervals
 setTimeout() - executes a function, once, after waiting a specified number of milliseconds

Note: The setInterval() and setTimeout() are both methods of the HTML DOM Window object.

The setInterval() Method

The setInterval() method will wait a specified number of milliseconds, and then execute a
specified function, and it will continue to execute the function, once at every given time-interval.

Syntax
setInterval("javascript function",milliseconds);

The first parameter of setInterval() should be a function.

The second parameter indicates the length of the time-intervals between each execution.

Note: There are 1000 milliseconds in one second.

Example

Alert "hello" every 3 seconds:

<!DOCTYPE html>

<html>

<body>
<p>Click the button to wait 3 seconds, then alert "Hello".</p>

<p>After clicking away the alert box, an new alert box will appear in 3 seconds. This goes on
forever...</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction()

setInterval(function(){alert("Hello")},3000);

</script>

</body>

</html>

The example show you how the setInterval() method works, but it is not very likely that you
want to alert a message every 3 seconds.

Below is an example that will display the current time. The setInterval() method is used to
execute the function once every 1 second, just like a digital watch.

Example

Display the current time:


<!DOCTYPE html>

<html>

<body>

<p>Click the button to display the current time.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction()

setInterval(function(){myTimer()},1000);

function myTimer()

var d=new Date();

var t=d.toLocaleTimeString();

document.getElementById("demo").innerHTML=t;

</script>

<p id="demo"></p>

</body>

</html>
How to Stop the Execution?

The clearInterval() method is used to stop further executions of the function specified in the
setInterval() method.

Syntax
clearInterval(intervalVariable)

To be able to use the clearInterval() method, you must use a global variable when creating the
interval method:

myVar=setInterval("javascript function",milliseconds);

Then you will be able to stop the execution by calling the clearInterval() method.

Example

Same example as above, but we have added a "Stop the timer" button:

<!DOCTYPE html>

<html>

<body>

<p>Click the first button to display the current time, and the second button to stop the time.</p>

<button onclick="myFunction()">Try it</button>

<button onclick="myStopFunction()">Stop time</button>

<script>

var myVar;

function myFunction()

myVar=setInterval(function(){myTimer()},1000);

}
function myTimer()

var d=new Date();

var t=d.toLocaleTimeString();

document.getElementById("demo").innerHTML=t;

function myStopFunction()

clearInterval(myVar);

</script>

<p id="demo"></p>

</body>

</html>

The setTimeout() Method


Syntax
setTimeout("javascript function",milliseconds);

The setTimeout() method will wait the specified number of milliseconds, and then execute the
specified function.

The first parameter of setTimeout() should be a function.

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

<!DOCTYPE html>

<html>

<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction()

setTimeout(function(){alert("Hello")},3000);

</script>

</body>

</html>

How to Stop the Execution?

The clearTimeout() method is used to stop the execution of the function specified in the
setTimeout() method.

Syntax
clearTimeout(timeoutVariable)

To be able to use the clearTimeout() method, you must use a global variable when creating the
timeout method:

myVar=setTimeout("javascript function",milliseconds);
Then, if the function has not allready being executed, you will be able to stop the execution by
calling the clearTimeout() method.

Example

Same example as above, but we have added a "Stop the alert" button:

<!DOCTYPE html>

<html>

<body>

<p>Click the first button alert "Hello" after waiting 3 seconds.</p>

<p>Click the second button to prevent the first function to execute. (You must click it before the 3
seconds are up.)</p>

<button onclick="myFunction()">Try it</button>

<button onclick="myStopFunction()">Stop the alert</button>

<script>

var myVar;

function myFunction()

myVar=setTimeout(function(){alert("Hello")},3000);

function myStopFunction()

clearTimeout(myVar);

}
</script>

</body>

</html>

You might also like