【JavaScript】使用setInterval()函數作簡單的輪詢操作,setinterval輪詢

來源:互聯網
上載者:User

【JavaScript】使用setInterval()函數作簡單的輪詢操作,setinterval輪詢

輪詢(Polling)是一種CPU決策如何提供周邊裝置服務的方式,又稱“程式控制輸出入”(Programmed I/O)。輪詢法的概念是,由CPU定時發出詢問,依序詢問每一個周邊裝置是否需要其服務,有即給予服務,服務結束後再問下一個周邊,接著不斷周而復始。輪詢法實作容易,但效率偏低。

在JavaScript使用setInterval函數作簡單的輪詢操作,可以隨時判定某一個參數值,但不用重新整理頁面,即不用在頁頭加入<META HTTP-EQUIV="Refresh" CONTENT="5">作重新整理頁面的判定。


一、基本目標

的一個輸入框,不用onChange()函數,直接使用setInterval函數作簡單的輪詢操作,沒隔0.5秒去讀取文字框裡的內容


其實原理與JavaScript時鐘一樣,每一秒取現在的時間,然後更新一次常值內容


二、製作過程

代碼如下,不再贅述了:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Polling</title><script type="text/javascript">function synchronous() {document.getElementById("ptext").innerHTML =document.getElementById("text").value;}function Polling(){synchronous();setInterval("synchronous()", 500);}</script></head><body onLoad="Polling()"><input type="text" id="text"/><p id="ptext"></p></body></html>
polling()函數在頁面載入完畢之後就開始執行,先執行完synchronous()函數,之後永遠在每隔0.5秒就執行一次synchronous();函數


JAVASCRIPT setInterval操作

<html>
<body>
<div id="one" > 5</div>
<script>
var i=5;
var one=document.getElementById("one");
var si = setInterval(function(){
one.innerText=i--;
if (i == 0) clearInterval(si);
},1000)
</script>
</body>
</html>
 
javascript怎清除另一個函數中的setInterval?

//1樓2樓完全錯誤。在計時器調用中是show(),你並沒有聲明該函數,產生錯誤的計時器。代碼必定出錯。

var timer1 = null;

function start(){
if ( timer1 )
return;
timer1 = setInterval("test()",200);
}
function end(){
if ( timer1 )
{
clearInterval(timer1);
timer1 = null;
}
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.