04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8: The Browser Object Model<br />

When setTimeout() is called, it returns a numeric ID for the timeout. The timeout ID is a unique<br />

identifier for the scheduled code that can be used to cancel the timeout. To cancel a pending timeout, use<br />

the clearTimeout() method and pass in the timeout ID as in the following example:<br />

//set the timeout<br />

var timeoutId = setTimeout(function() {<br />

alert(“Hello world!”);<br />

}, 1000);<br />

//nevermind - cancel it<br />

clearTimeout(timeoutId);<br />

As long as clearTimeout() is called before the specified amount of time has passed, a timeout can be<br />

canceled completely. Calling clearTimeout() after the code has been executed has no effect.<br />

All code executed by a timeout runs in the global scope, so the value of this inside the function will<br />

always point to window .<br />

Intervals work in the same way as timeouts except that they execute the code repeatedly at specific time<br />

intervals until the interval is canceled or the page is unloaded. The setInterval() method lets you set<br />

up intervals, and it accepts the same arguments as setTimeout() : the code to execute (string or<br />

function) and the amount of time in milliseconds to wait between executions. Here ’ s an example:<br />

//avoid!<br />

setInterval(“alert(‘Hello world!’) “, 10000);<br />

//preferred<br />

setInterval(function() {<br />

alert(“Hello world!”);<br />

}, 10000);<br />

The setInterval() method also returns an interval ID that can be used to cancel the interval at some<br />

point in the future. The clearInterval() method can be used with this ID to cancel all pending<br />

intervals. This ability is more important for intervals than timeouts since, if left unchecked, they continue<br />

to execute until the page is unloaded. Here is a common example of interval usage:<br />

var num = 0;<br />

var max = 10;<br />

var intervalId = null;<br />

function incrementNumber() {<br />

num++;<br />

}<br />

//if the max has been reached, cancel all pending executions<br />

if (num == max) {<br />

clearInterval(intervalId);<br />

alert(“Done”);<br />

}<br />

intervalId = setInterval(incrementNumber, 500);<br />

212

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!