潇湘沐
更好地利用詹迪氏回答实现轮询功能,该功能将轮询每个interval几秒钟后结束timeout几秒钟。function pollFunc(fn, timeout, interval) {
var startTime = (new Date()).getTime();
interval = interval || 1000;
(function p() {
fn();
if (((new Date).getTime() - startTime ) <= timeout) {
setTimeout(p, interval);
}
})();}pollFunc(sendHeartBeat, 60000, 1000);更新根据注释,更新它以了解传递函数停止轮询的能力:function pollFunc(fn, timeout, interval) {
var startTime = (new Date()).getTime();
interval = interval || 1000,
canPoll = true;
(function p() {
canPoll = ((new Date).getTime() - startTime ) <= timeout;
if (!fn() && canPoll) { // ensures the function exucutes
setTimeout(p, interval);
}
})();}pollFunc(sendHeartBeat, 60000, 1000);function sendHeartBeat(params) {
...
...
if (receivedData) {
// no need to execute further
return true; // or false, change the IIFE inside condition accordingly.
}}