15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Chapter 2 ✦ Window and Frame Objects (Chapter 16)<br />

theTime += (theHour >= 12) ? “ pm” : “ am”<br />

theTime += ((flasher) ? “ “ : “*”)<br />

flasher = !flasher<br />

window.status = theTime<br />

// recursively call this function every second to keep timer going<br />

timerID = setTimeout(“updateTime()”,1000)<br />

}<br />

//--><br />

<br />

<br />

<br />

<br />

<br />

In this function, the setTimeout() method works in the following way: Once the<br />

current time (including the flasher status) appears in the statusbar, the function<br />

waits approximately one second (1,000 milliseconds) before calling the same function<br />

again. You don’t have to clear the timerID value in this application because<br />

<strong>JavaScript</strong> does it for you every time the 1,000 milliseconds elapse.<br />

A logical question to ask is whether this application should be using<br />

setInterval() instead of setTimeout(). This is a case in which either one does<br />

the job. To use setInterval() here would require that the interval process start<br />

outside of the updateTime() function, because you need only one process running<br />

that repeatedly calls updateTime(). It would be a cleaner implementation in that<br />

regard, instead of the tons of timeout processes spawned by Listing 16-38. On the<br />

other hand, the application would not run in any browsers before NN4 or IE4, as<br />

Listing 16-38 does.<br />

To demonstrate passing parameters, you can modify the updateTime() function<br />

to add the number of times it gets invoked to the display in the statusbar. For that<br />

to work, the function must have a parameter variable so that it can catch a new<br />

value each time it is invoked by setTimeout()’s expression. For all browsers, the<br />

function would be modified as follows (unchanged lines are represented by the<br />

ellipsis):<br />

function updateTime(i) {<br />

...<br />

window.status = theTime + “ (“ + i + “)”<br />

// pass updated counter value with next call to this function<br />

timerID = setTimeout(“updateTime(“ + i+1 + “)”,1000)<br />

}<br />

If you were running this exclusively in NN4+, you could use its more convenient way<br />

of passing parameters to the function:<br />

timerID = setTimeout(updateTime,1000, i+1)<br />

In either case, the onLoad event handler would also have to be modified to get the<br />

ball rolling with an initial parameter:<br />

onLoad = “updateTime(0)”<br />

177<br />

windowObject.setTimeout()

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

Saved successfully!

Ooh no, something went wrong!