Skip to content

Commit

Permalink
Add an argument to the callback in PollingManager to stop the polling…
Browse files Browse the repository at this point in the history
… | refs #35772
  • Loading branch information
sdiemer committed Mar 1, 2024
1 parent 2080441 commit 17a9d72
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 11 deletions.
2 changes: 1 addition & 1 deletion dist/jsu.min.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/jsu.min.mjs

Large diffs are not rendered by default.

8 changes: 5 additions & 3 deletions src/lib/polling-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class PollingManager {
this.interval = interval;
this.fct = fct;

if (enabled === true || enabled === undefined) {
if (enabled === undefined || enabled === true) {
this.enable();
}
document.addEventListener('visibilitychange', function () {
Expand All @@ -51,10 +51,12 @@ export class PollingManager {
if (this.enabled && !this.running) {
this.running = true;
this.cancel();
this.fct(function () {
this.fct(function (planNext) {
this.lastRun = (new Date()).getTime();
this.running = false;
this.plan(this.interval);
if (planNext === undefined || planNext === true) {
this.plan(this.interval);
}
}.bind(this));
}
}
Expand Down
32 changes: 26 additions & 6 deletions tests/test_polling.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
const assert = require('assert');
import { PollingManager } from '../src/lib/polling-manager.js';

const sleep = (time) => {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
};

describe('PollingManager', () => {
it('should handle polling function', async () => {
const sleep = (time) => {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
};

const start = new Date().getTime();
const calls = [];
const polling = new PollingManager(function (callback) {
Expand Down Expand Up @@ -47,4 +47,24 @@ describe('PollingManager', () => {
// Cleanup test
polling.disable();
}).timeout(5000);
it('should handle planNext in callback', async () => {
const start = new Date().getTime();
const calls = [];
const polling = new PollingManager(function (callback) {
calls.push(new Date().getTime() - start);
callback(false);
}, 1000);

// Test call after init
await sleep(500);
assert(calls.length == 1);
assert(calls[0] < 100, `${calls[0]} ~= 0`);

// Test no call after first run because planNext=false
await sleep(1000);
assert(calls.length == 1);

// Cleanup test
polling.disable();
}).timeout(2000);
});

0 comments on commit 17a9d72

Please sign in to comment.