Sie sind auf Seite 1von 3

JavaScript Timing Events

1
2
3
4
5
6
7
8
9
10
11
12

JavaScript can be executed in time-intervals.
This is called timing events.
JavaScript Timing Events
With JavaScript, it is possible to execute some code after a specified time-interval. This is called
timing events.
It's ver eas to time events in JavaScript. The t!o "e 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 &T'( )*' Windo! ob+ect.
The setTimeout$% 'ethod
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 ou !ant to cancel this setTimeout$%, ou 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 li"e ,alert$'- seconds.'%, or a call to a function, li"e ,alert'sg$%,.
The second parameter indicates ho! man milliseconds from no! ou !ant to execute the first
parameter.
Note: There are /000 milliseconds in one second.
Example
When the button is clic"ed in the example belo!, an alert box !ill be displaed after - seconds.
Example
<html>
<head>
<script type="text/javascript">
function timeds!()
"
var t=setTimeout("alert(#$ seconds%#)",$&&&);
'
</script>
</head>
<(ody>
<form>
<input type="(utton" value=")isplay timed alert(ox%"
on*lic+="timeds!()" />
</form>
</(ody>
</html>
Example - Infinite (oop
To get a timer to !or" in an infinite loop, !e must !rite a function that calls itself. In the example
belo!, !hen the button is clic"ed, the input field !ill start to count $for ever%, starting at 0#
Example
<html>
<head>
<script type="text/javascript">
var c=&
var t
function timed*ount()
"
document,!et-lement.y/d(#txt#),value=c;
c=c01;
t=setTimeout("timed*ount()",1&&&);
'
</script>
</head>
<(ody>
<form>
<input type="(utton" value="2tart count%" on*lic+="timed*ount()" />
<input type="text" id="txt" />
</form>
</(ody>
</html>
The clearTimeout$% 'ethod
Syntax
clearTimeout(setTimeout_variable)
Example
The example belo! is the same as the ,Infinite (oop, example above. The onl difference is that !e
have no! added a ,Stop 1ount., button that stops the timer#
Example
<html>
<head>
<script type="text/javascript">
var c=&
var t
function timed*ount()
"
document,!et-lement.y/d(#txt#),value=c;
c=c01;
t=setTimeout("timed*ount()",1&&&);
'
function stop*ount()
"
clearTimeout(t);
'
</script>
</head>
<(ody>
<form>
<input type="(utton" value="2tart count%" on*lic+="timed*ount()" />
<input type="text" id="txt" />
<input type="(utton" value="2top count%" on*lic+="stop*ount()" />
</form>
</(ody>
</html>

Das könnte Ihnen auch gefallen