DPoll: Simple JavaScript Polling Library

DPoll is a lightweight JavaScript library for periodically fetching data from a server using AJAX. It is ideal for real-time updates, dashboards, and more.

Installation

Include the full source file:

<script src="https://lite.datahihi1.id.vn/js/DPoll/DPoll.js"></script>

Include the minified script in your HTML:

<script src="https://lite.datahihi1.id.vn/js/DPoll/DPoll.min.js"></script>

Or download the full source file from GitHub.

Usage Example

Below are several examples showing common usage patterns with DPoll.

1. Basic JSON polling

var poller = new DPoll({
    url: 'https://api.example.com/data',
    interval: 5000,
    onData: function(text) {
        // DPoll returns raw responseText; parse JSON if server returns JSON
        try {
            var data = JSON.parse(text);
            console.log('Received object:', data);
        } catch (e) {
            console.log('Raw response:', text);
        }
    },
    onError: function(err) {
        console.error('Polling error:', err);
    }
});

poller.start();
// poller.stop();

2. Dynamic URL (function)

var poller = new DPoll({
    url: function() {
        // attach timestamp or change endpoint dynamically
        return 'https://api.example.com/data?ts=' + Date.now();
    },
    interval: 3000,
    onData: function(text) { console.log(text); }
});
poller.start();

3. Simple retry/backoff on error

// increase interval on consecutive errors
var retryCount = 0;
var base = 2000;
var poller = new DPoll({
    url: 'https://api.example.com/data',
    interval: base,
    onData: function(text) {
        retryCount = 0; // reset on success
        console.log('OK:', text);
    },
    onError: function(err) {
        retryCount++;
        var next = Math.min(30000, base * Math.pow(2, retryCount));
        poller.interval = next; // adjust interval for backoff
        console.error('Error, backing off to', next);
    }
});
poller.start();

4. Use DPoll with a DOM update (live demo)

Latest response

(no data yet)

The demo below uses the public Chuck Norris Jokes API as an example endpoint. Replace the URL with your API.