Polling Understanding
In fact, the focus of polling is how many times it takes to be executed once, not the loop itself. ajax is an asynchronous request. The process from initiating a request to receiving a response is a complete process. The time required for this process is unpredictable. To the extreme point, if the time required for the request exceeds the interval between our polling, then many problems will occur. Therefore, the interval between polling should be based on ensuring that the request process is completed, which is more logical.
Business Description:
- Page initialization displays the first page data, and then the current page data is refreshed every ten seconds
- Change the filter criteria or change the page number to refresh the data directly, and then the current data will be refreshed every ten seconds.
Business logic point analysis:
- When manually invoked, immediately execute the initiation request
- Then execute every ten seconds, refreshing the list
Implementation ideas
- Call the request first
- Set timer setTimeout in the requested successful callback function
- Repeat 1.2 operation within the timer
- Encapsulate step 1.2.3 as a recursive function
// Polling method polling (page) { (page).then(res => { = setTimeout(() => { clearTimeout() (page) }, 10000) }) }
Why not use setInterval
The function of setInterval seems to be perfectly in line with the concept of polling. If our operation is synchronized code, then there is no problem with using setInterval. The problem lies in that setInterval is not flexible enough, and we cannot know whether the last request has been completed. So setTimeout would be better.
Things to note
During the polling, I recorded the timer with pollingST variable. Before each execution, I must clear the previous timer. Because the recursive call is inside the timer, so the polling can be easily ended by clearing the timer.
Complete pseudo-code
<script> export default { data () { return { pollingST: null } }, methods: { // Pagination change event pageChange (params) { // Clear the existing timer clearTimeout() // Call polling (params) }, // Request interface method getWorks () { return new Promise(resolve => resolve({})) }, // Polling method polling (params) { (params).then(res => { = setTimeout(() => { clearTimeout() (params) }, 10000) }) } }, created () { // Call polling ({ page: 1, pageSize: 5 }) }, destroyed () { clearTimeout() } } </script>
Summarize
This is all about this article about vue polling solutions. For more related vue polling solutions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!