LEARNING JAVASCRIPT - Trang 225

}

setTimeout

(

f

,

60

*

1000

);

// one minute

console

.

log

(

"I happen after setTimeout!"

);

console

.

log

(

"Me too!"

);

If you run this at the console—unless you are a very slow typist indeed—you should

see something like this:

Before timeout: Sun Aug 02 2015 17:11:32 GMT-0700 (Pacific Daylight Time)
I happen after setTimeout!
Me too!
After timeout: Sun Aug 02 2015 17:12:32 GMT-0700 (Pacific Daylight Time)

What beginners struggle with is the disconnect between the linear nature of the code

we write and the actual execution of that code. There is a part of us that wants—that

expects—a computer to do things in the exact order in which we write them. In other

words, we want to see this:

Before timeout: Sun Aug 02 2015 17:11:32 GMT-0700 (Pacific Daylight Time)
After timeout: Sun Aug 02 2015 17:12:32 GMT-0700 (Pacific Daylight Time)
I happen after setTimeout!
Me too!

We may want to see that…but it wouldn’t be asynchronous. The whole point of asyn‐

chronous execution is that it doesn’t block anything. Because JavaScript is single-

threaded, if we told it to wait for 60 seconds before doing some code, and we did that

synchronously, nothing would work. Your program would freeze up: it wouldn’t

accept user input, it wouldn’t update the screen, and so on. We’ve all had this experi‐

ence, and it’s not desirable. Asynchronous techniques help prevent this kind of

lock-up.
In this example, for clarity, we used a named function to pass to

setTimeout

. Unless

there were some compelling reason to have a named function, we would normally

just use an anonymous function:

setTimeout

(

function

() {

console

.

log

(

"After timeout: "

+

new

Date

());

},

60

*

1000

);

setTimeout

is a little bit problematic because the numeric timeout parameter is the

last argument; with anonymous functions, especially if they’re long, it can get lost or

look like it’s part of the function. This is common enough, however, that you’ll have

to get used to seeing

setTimeout

(and its companion,

setInterval

) used with

anonymous functions. Just remember that the last line contains the delay parameter.

setInterval and clearInterval

In addition to

setTimeout

, which runs its function once and stops, there’s

setInterval

, which runs the callback at the specified interval forever, or until you

Callbacks | 201

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.