THE BOOK OF JAVASCRIPT, 2ND EDITION phần

Dòng khởi setTimeout (). Mười giây sau, trừ khi clearTimeout () hủy bỏ thời gian ra my_timeout, goToAnswerPage chức năng (), được xác định, được gọi là. Chức năng này gọi lên một hộp cảnh báo và gửi các cầu thủ . Dòng định nghĩa checkAnswer (), hàm được gọi khi người chơi nộp một câu trả lời (). | form onSubmit checkAnswer my_timeout return false input type text name the_answer input type submit value answer form body html Figure 9-3 A riddle game Line-by-Line Analysis of Figure 9-3 Line o initiates setTimeout . Ten seconds later unless clearTimeout cancels the time-out called my_timeout the function goToAnswerPage defined in is called. This function calls up an alert box and sends the player to . Line defines checkAnswer the function called when the player submits an answer . checkAnswer takes two parameters the answer that the player submits and the time-out to cancel if the answer is correct. The first line of the function checks the answer. If it s correct cancels the time-out which stops JavaScript from calling the goToAnswerPage function and congratulates the player. If which calls the checkAnswer function when the player submits the form seems unfamiliar look at Handling Events Using Form Elements on page 116 which discusses the onSubmit event. Figure 9-4 shows the riddle game in action. NOTE If you want to run this script you ll need to create the page which is just a normal web page with the riddle s answer on it. Figure 9-4 What the riddle game looks like Repeating Timed Actions You ve already seen examples of repeating timed actions. The tip box discussed in the section How the Book of JavaScript Tip Box Works on page 136 displays each tip for seconds and the text box that tells you how long you ve been on the page updates every second. Both of these examples use the same mechanism. As you have just seen in Chapter 8 the usual way to get JavaScript to perform an action repeatedly is to put the action into a loop. Unfortunately we can t use a while or for loop for repeated timed events. The while and for loops run too quickly and there s no good way to slow them down. Even if you could slow them there s no way to time these loops accurately because 150 Chapter 9 they run at different speeds on .

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
187    157    10    21-05-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.