ตัวอย่างโค้ดต่อไปนี้ใช้ ในกรณี ให้ส่งค่าข้อมูล หรือทำงานคำสั่งที่ต้องการ
หลังจากการพิมพ์ข้อมูล ตัวสุดท้ายแล้ว 3 วินาที (สามารถกำหนดเวลาตามต้องการ)
เหมือนกับให้โปรแกรมทำงาน หลังจากพิมพ์ข้อมูลตัวสุดท้ายแล้วเท่านั้น ซึ่งโดยปกติ หาก
ไม่ได้กำหนดโค้ดตามนี้ คำสั่งต่างๆ จะทำงานทันทึเมื่อกดพิมพ์ข้อมูล แม้ว่าข้อมูลยังทำการพิมพ์ยังไม่เสร็จ
ตัวอย่างโค้ดที่ทำงานทันทีเมื่อทำการพิมพ์ข้อมูล
<form id="form1" name="form1" method="post" action="">
<input name="sample_input" type="text" id="sample_input" size="40" />
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function(){
$("#sample_input").keyup(function(event){
var input_data=$("#sample_input").val();
alert(input_data);
});
});
</script>
ตัวอย่าง
ตัวอย่างโค้ดกรณีหน่วงเวลา ให้ทำงานหลังจากพิมพ์ข้อมูลตัวสุดท้ายแล้ว 3 วินาที
<form id="form1" name="form1" method="post" action="">
<input name="sample_input" type="text" id="sample_input" size="40" />
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function(){
var delayID=null;
$("#sample_input").keyup(function(event){
if(delayID==null){
delayID=setTimeout(function(){
var input_data=$("#sample_input").val();
alert(input_data);
delayID=null;
},3000);
}else{
if(delayID){
clearTimeout(delayID);
delayID=setTimeout(function(){
var input_data=$("#sample_input").val();
alert(input_data);
delayID=null;
},3000);
}
}
});
});
</script>
ตัวอย่าง