18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

takes a little bit of time before that friendly yellow box appears to tell you what the button does. If you<br />

move your mouse over the button for just a short time and then move it to another button, the tooltip<br />

isn’t displayed. This is precisely why you would cancel a timeout before the code executes: Because you<br />

want to wait a specified amount of time before the code is executed. If the user does something that<br />

would result in a different outcome, you need the flexibility to cancel that timeout.<br />

Intervals work in much the same way except that they repeat the given code indefinitely at specific time<br />

intervals. To set up an interval, use the setInterval() method with the same type of arguments as you<br />

use with setTimeout() — the code to execute and the number of milliseconds to wait between each<br />

execution. <strong>For</strong> example:<br />

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

setInterval(function() { alert(“Hello world!”); }, 1000);<br />

function sayHelloWorld() {<br />

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

}<br />

setInterval(sayHelloWorld, 1000);<br />

Also similar to timeouts, the setInterval() method creates an interval ID to identify the code to be executed.<br />

It can be used with the clearInterval() method to prevent any further executions. Obviously,<br />

this is much more important when using intervals because, if left unchecked, they continue to execute<br />

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

var iNum = 0;<br />

var iMax = 100;<br />

var iIntervalId = null;<br />

function incNum() {<br />

iNum++;<br />

<strong>JavaScript</strong> in the Browser<br />

}<br />

if (iNum == iMax) {<br />

clearInterval(iIntervalId);<br />

}<br />

iIntervalId = setInterval(incNum, 500);<br />

In this code, the number iNum is incremented every 500 milliseconds until it reaches the maximum<br />

(iMax), at which point the interval is cleared. You can use timeouts for this, eliminating the need to keep<br />

track of a timeout ID, by doing the following:<br />

var iNum = 0;<br />

var iMax = 100;<br />

function incNum() {<br />

iNum++;<br />

}<br />

if (iNum != iMax) {<br />

setTimeout(incNum, 500);<br />

}<br />

setTimeout(incNum, 500);<br />

147

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

Saved successfully!

Ooh no, something went wrong!