pacman, rainbows, and roller s

Bài 16: Thiết lập thời gian chạy

Bài 16: Thiết lập thời gian chạy



JavaScript có thể thực hiện một chức năng nào đó sau một thời gian được định trước.

setTimeout() - Thực hiện một số lệnh với thời gian được định trước trong tương lai.clearTimeout() - Hủy hàm setTimeout()
Cú pháp:

Mã PHP: 

setTimeout("javascript statement",milliseconds); Với milliseconds * 1000 = 1 giây 

Ví dụ 1: Hiển thị hộp thoại alert sau 5 giây sau khi nhấn nút 

Mã PHP: 

<html> 
<head> 
<script type="text/javascript"> 
 var t; 
 function timedMsg(){ t=setTimeout("alert('5 seconds!')",5000); 
 } </script> </head> 
<body> 
 <form> 
 <input type="button" value="Display timed alertbox!" onClick="timedMsg()" /> 
 </form> 
</body> 
</html> 

Ví dụ 2: Tạo một ô textbox và có giá trị thay đổi theo thời gian

Mã PHP: 

<html> 
<head> 
<script type="text/javascript"> 
 var c=0; 
 var t; 
 function timedCount(){ document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()",1000); 
 } </script> 
</head> 
 
<body> 
<form> 
 <input type="button" value="Start count!" onClick="timedCount()"> 
 <input type="text" id="txt" /> 
</form> 
</body> 
</html> 

Ví dụ 3: Dừng giá trị trong ô textbox trong ví dụ 2

Mã PHP: 

<html> 
<head> 
<script type="text/javascript"> 
 var c=0; 
 var t; 
 function timedCount(){ document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()",1000); 
 } 
 function stopCount() 
 { clearTimeout(t); 
 } </script> </head> 
<body> 
<form> 
 <input type="button" value="Start count!" onClick="timedCount()"> 
 <input type="text" id="txt"> 
 <input type="button" value="Stop count!" onClick="stopCount()"> 
</form> 
</body> 
</html> 

Ví dụ 4: Ẩn hiện một bức tranh kết hợp setTimeout() và thuộc tính opacity của CSS

Mã PHP: 

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
<script type="text/javascript"> 
 var maxOpacity = 1; 
 var minOpacity = 0; 
 
 function setHidden(){ 
 var thisObj = document.getElementById('picture'); maxOpacity = maxOpacity - 0.1; 
 if(maxOpacity >= 0){ thisObj.style.opacity = maxOpacity; //thisObj.filters.alpha.opacity = maxOpacity; window.setTimeout("setHidden('picture')",100); 
 }else{ thisObj.style.opacity = 0; 
 } 
 } 
 
 function setShow(){ 
 var thisObj = document.getElementById('picture'); minOpacity = minOpacity + 0.1; 
 if(minOpacity <= 1){ thisObj.style.opacity = minOpacity; //thisObj.filters.alpha.opacity = maxOpacity; window.setTimeout("setShow('picture')",100); 
 }else{ thisObj.style.opacity = 1; 
 }

 

Copyright © 20012-2013 by 2Thangban
Powered by Xtgem
Design by PhamKhuong
Số người Người đang online 1
Số lượt xem trong tháng: 1
Tổng số lượt truy cập: 169
Chuyên mục:6
Bài Viết :
In trang này

Chia sẽ với Facebook

Chia Sẽ Cùng Twitter
Chia Sẽ cùng Google+

Chia sẽ cùng Zing

Chia sẽ cùng Yahoo