I have written a small JavaScript function which performs an AJAX request every x seconds.
I was hoping some of you could give it a look over and give me any pointers on redundant code or bad practices.
The idea of the function is to:
- Allow for polling to be initiated
- Once initiated, poll once every x seconds and perform an AJAX request.
- Stop polling once
disablePolling()
is executed. - Be able to be reused anywhere.
requester.js
function Request() {
this.poll = false;
this.activatePoll = function () {
this.poll = true;
this.runPoll();
};
this.disablePoll = function () {
this.poll = false;
};
this.runPoll = function () {
var self = this;
var poll = setTimeout(function () {
$.ajax({
url: './request.php',
success: function (response) {
console.log(response);
},
dataType: "json",
complete: function () {
if (self.poll == false) {
clearTimeout(poll);
} else {
self.runPoll();
}
}
})
}, 1000);
};
}
Usage:
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Requester</title> </head> <body> <h1>Requester</h1> <div id="requester"> <input type="button" onclick="$request.test();" value="test"> <input type="button" onclick="$request.activatePoll();" value="poll"> <input type="button" onclick="$request.disablePoll();" value="turn off poll"> </div> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="js/request.js"></script> <script> $(document).ready(function () { $request = new Request(); }); </script> </html>
request.php
<?php echo json_encode($time()); ?>
It should also be mentioned that theAajax request will need to also POST some parameters.