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 />

In this example, the variable num is incremented every half second until it finally reaches the maximum<br />

number, at which point the interval is canceled. This pattern can also be implemented using timeouts, as<br />

shown here:<br />

var num = 0;<br />

var max = 10;<br />

function incrementNumber() {<br />

num++;<br />

}<br />

//if the max has not been reached, set another timeout<br />

if (num < max) {<br />

setTimeout(incrementNumber, 500);<br />

} else {<br />

alert(“Done”);<br />

}<br />

setTimeout(incrementNumber, 500);<br />

Note that when you’re using timeouts, it is unnecessary to track the timeout ID, because the execution<br />

will stop on its own and continue only if another timeout is set. This pattern is considered a best practice<br />

for setting intervals without actually using intervals. True intervals are rarely used in production<br />

environments because it ’ s possible that one interval will begin before the previous one has finished<br />

executing. Using timeouts, as in the preceding example, ensures that can ’ t happen. Generally speaking,<br />

it ’ s best to avoid intervals.<br />

System Dialogs<br />

The browser is capable of invoking system dialogs to display to the user through the alert() ,<br />

confirm() , and input() methods. These dialogs are not related to the web page being displayed in the<br />

browser and do not contain HTML. Their appearance is determined by operating - system and/or<br />

browser settings rather than CSS. Additionally, each of these dialogs is synchronous and modal, meaning<br />

code execution stops when a dialog is displayed, and resumes after it has been dismissed.<br />

The alert() method has been used throughout this book. It simply accepts a string to display to the<br />

user. When alert() is called, a system message box displays the specified text to the user, followed by a<br />

single OK button. For example, alert( “ Hello world! “ ) renders the dialog box shown in Figure 8 - 3<br />

when used with IE on Windows XP.<br />

Figure 8-3<br />

213

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

Saved successfully!

Ooh no, something went wrong!