Skip to content

script-php/adaptivePoller

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

AdaptivePoller

A lightweight, flexible JavaScript polling library that supports adaptive polling intervals and works in both browser and Node.js environments.

Features

  • Adaptive Polling: Dynamically adjust polling intervals based on server responses
  • Universal Compatibility: Works in browsers, Node.js, and AMD environments
  • Configurable: Customizable endpoints, intervals, and request data
  • Callback Support: Success, error, and completion callbacks
  • Runtime Control: Start, stop, restart, and update configuration on the fly
  • Status Monitoring: Check if polling is currently active
  • Error Handling: Built-in error handling with customizable callbacks

Installation

Browser

<script src="adaptivePoller.js"></script>

AMD (RequireJS)

require(['adaptivePoller'], function(adaptivePoller) {
    // Use adaptivePoller
});

Basic Usage

// Initialize and start polling
const poller = adaptivePoller.start({
    endpoint: 'https://api.example.com/status',
    timeInterval: 30000, // Poll every 30 seconds
    data: { userId: 123 },
    onSuccess: function(response) {
        console.log('Success:', response);
    },
    onError: function(error) {
        console.error('Error:', error);
    }
});

Configuration Options

Option Type Default Description
timeInterval Number 60000 Polling interval in milliseconds
endpoint String 'process-data.php' API endpoint URL
data Object {} Data to send with each request
onSuccess Function null Callback for successful responses
onError Function null Callback for errors
onComplete Function null Callback that runs after every request

API Methods

start(config)

Starts polling with optional initial configuration.

adaptivePoller.start({
    endpoint: '/api/data',
    timeInterval: 15000,
    data: { token: 'abc123' }
});

stop()

Stops the current polling process.

adaptivePoller.stop();

restart()

Restarts polling using the existing configuration.

adaptivePoller.restart();

updateConfig(newConfig)

Updates the configuration while polling is running.

adaptivePoller.updateConfig({
    timeInterval: 45000,
    data: { newParam: 'value' }
});

getConfig()

Returns a copy of the current configuration.

const currentConfig = adaptivePoller.getConfig();
console.log(currentConfig);

setCallbacks(callbacks)

Updates callback functions.

adaptivePoller.setCallbacks({
    onSuccess: function(response) {
        console.log('New success handler:', response);
    },
    onError: function(error) {
        console.error('New error handler:', error);
    },
    onComplete: function() {
        console.log('Request completed');
    }
});

isPolling()

Returns whether polling is currently active.

if (adaptivePoller.isPolling()) {
    console.log('Polling is active');
}

Adaptive Polling

The library supports adaptive polling intervals. Your server can return a configuration object to modify polling behavior:

Server Response Example:

{
    "data": { "status": "processing" },
    "config": {
        "timeInterval": 10000
    }
}

This response will update the polling interval to 10 seconds for subsequent requests.

Advanced Examples

Real-time Status Monitoring

const statusPoller = adaptivePoller.start({
    endpoint: '/api/job-status',
    timeInterval: 5000,
    data: { jobId: 'job_123' },
    onSuccess: function(response) {
        if (response.status === 'completed') {
            console.log('Job completed!');
            statusPoller.stop();
        } else if (response.status === 'processing') {
            console.log('Job still processing...');
        }
    },
    onError: function(error) {
        console.error('Failed to check status:', error);
        // Optionally stop polling on persistent errors
        if (error.status === 404) {
            statusPoller.stop();
        }
    }
});

Dynamic Configuration Updates

const poller = adaptivePoller.start({
    endpoint: '/api/metrics',
    timeInterval: 60000
});

// Update configuration based on user interaction
document.getElementById('urgent-mode').addEventListener('click', function() {
    poller.updateConfig({
        timeInterval: 5000, // Poll every 5 seconds in urgent mode
        data: { priority: 'high' }
    });
});

document.getElementById('normal-mode').addEventListener('click', function() {
    poller.updateConfig({
        timeInterval: 60000, // Back to normal polling
        data: { priority: 'normal' }
    });
});

Chaining Methods

adaptivePoller
    .updateConfig({ endpoint: '/api/v2/data' })
    .setCallbacks({
        onSuccess: (response) => console.log('Success:', response),
        onError: (error) => console.error('Error:', error)
    })
    .start();

Error Handling

The library provides detailed error information:

adaptivePoller.start({
    endpoint: '/api/data',
    onError: function(error) {
        console.error('Status:', error.status);
        console.error('Status Text:', error.statusText);
        console.error('Response:', error.response);
        
        // Handle specific error cases
        if (error.status === 429) {
            console.log('Rate limited, slowing down...');
            adaptivePoller.updateConfig({ timeInterval: 120000 });
        }
    }
});

Browser Compatibility

  • Chrome 32+
  • Firefox 29+
  • Safari 9+
  • Edge 12+
  • Internet Explorer 9+

Node.js Compatibility

Requires Node.js 8.0 or higher.

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Changelog

v1.0.0

  • Initial release
  • Basic polling functionality
  • Adaptive interval support
  • Universal module support
  • Comprehensive callback system

About

A lightweight, flexible JavaScript polling library that supports adaptive polling intervals and works in both browser and Node.js environments.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors