This article describes the method of JavaScript using the setInterval() function to implement a simple polling operation. Share it for your reference. The specific analysis is as follows:
Polling is a way for CPU to decide how to provide peripheral equipment services, also known as "Programmed I/O". The concept of polling method is that the CPU issues inquiry regularly, asking each peripheral device in sequence whether it needs its services, and when there is, the service is given. After the service is over, the next peripheral will be asked, and then it will continue to repeat. The polling method is easy to implement, but it is relatively inefficient.
In JavaScript, use the setInterval function for a simple polling operation. You can determine a certain parameter value at any time, but you don’t need to refresh the page, that is, you don’t need to add <META HTTP-EQUIV="Refresh" CONTENT="5"> to the header to make the page refresh judgment.
1. Basic Objectives
As shown in the input box in the figure, you do not use the onChange() function, and use the setInterval function to perform a simple polling operation. You can read the contents in the text box every 0.5 seconds.
In fact, the principle is the same as the JavaScript clock. Take the current time every second and then update the text content once.
2. Production process
The code is as follows, I won't repeat it again:
Copy the code as follows:<!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>
The polling() function starts to be executed after the page is loaded. The synchronous() function is executed first, and then the synchronous() function is executed every 0.5 seconds.
I hope this article will be helpful to everyone's JavaScript programming.