Java Reference
In-Depth Information
Timing Functions
The window object provides some useful methods for scheduling the execution of a func-
tion and for repeatedly executing functions at regular intervals.
The window.setTimeout() method accepts a callback to a function as its first paramet-
er and a number of milliseconds as its second parameter. Try entering the following example
into a console. It should show an alert dialog after three seconds (that's 3000 milliseconds):
window.setTimeout(function(){ alert("Time's Up!") }, 3000);
<< 4
Notice that the method returns an integer. This is an ID used to reference that particular
timeout. It can also cancel the timeout using the window.clearTimeout() method. Try
calling the code again:
window.setTimeout(function(){ alert("Time's Up!") }, 3000);
<< 5
Now quickly enter the following code before the alert pops up:
window.clearTimeout(5); // make sure you use the correct ID
<< undefined
If you were quick enough, and used the correct ID, the alert was prevented from happening.
The window.setInterval() method works in a similar way to win-
dow.setTimeout() , except that it will continue to invoke the callback function after
every given number of milliseconds.
The previous example used an anonymous function, but it is also possible to use a named
function like so:
function hello(){ console.log("Hello"); };
Now we can set up the interval and assign it to a variable:
Search WWH ::




Custom Search