├── .eslintignore ├── tsconfig.release.json ├── .prettierrc ├── .editorconfig ├── .gitignore ├── .github └── workflows │ └── nodejs.yml ├── jest.config.js ├── .eslintrc.json ├── tsconfig.json ├── README.md ├── LICENSE ├── __tests__ └── main.test.ts ├── src └── Backoff.ts └── package.json /.eslintignore: -------------------------------------------------------------------------------- 1 | /**/*.js 2 | /**/*.d.ts -------------------------------------------------------------------------------- /tsconfig.release.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "rootDir": "./src", 5 | "outDir": "build", 6 | "removeComments": true 7 | }, 8 | "include": ["src/**/*"] 9 | } 10 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all", 4 | "overrides": [ 5 | { 6 | "files": "*.ts", 7 | "options": { 8 | "parser": "typescript" 9 | } 10 | } 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | trim_trailing_whitespace = true 7 | insert_final_newline = true 8 | 9 | [*.md] 10 | insert_final_newline = false 11 | trim_trailing_whitespace = false 12 | 13 | [*.{js,jsx,json,ts,tsx,yml}] 14 | indent_size = 2 15 | indent_style = space 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Dependencies 7 | node_modules/ 8 | 9 | # Coverage 10 | coverage 11 | 12 | # Transpiled files 13 | build/ 14 | 15 | # VS Code 16 | .vscode 17 | !.vscode/tasks.js 18 | 19 | # JetBrains IDEs 20 | .idea/ 21 | 22 | # Optional npm cache directory 23 | .npm 24 | 25 | # Optional eslint cache 26 | .eslintcache 27 | 28 | # Misc 29 | .DS_Store -------------------------------------------------------------------------------- /.github/workflows/nodejs.yml: -------------------------------------------------------------------------------- 1 | name: Node.js CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v2 12 | - uses: volta-cli/action@v1 13 | - run: npm ci --no-audit 14 | - run: npm run lint --if-present 15 | - run: npm test 16 | - run: npm run build --if-present 17 | env: 18 | CI: true 19 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | testEnvironment: 'node', 3 | transform: { 4 | "^.+\\.tsx?$": "ts-jest" 5 | }, 6 | moduleFileExtensions: [ 7 | "ts", 8 | "tsx", 9 | "js", 10 | "jsx", 11 | "json", 12 | "node", 13 | ], 14 | testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(ts|js)x?$', 15 | coverageDirectory: 'coverage', 16 | collectCoverageFrom: [ 17 | 'src/**/*.{ts,tsx,js,jsx}', 18 | '!src/**/*.d.ts', 19 | ], 20 | }; 21 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": false, 4 | "es6": true, 5 | "node": true 6 | }, 7 | "parser": "@typescript-eslint/parser", 8 | "parserOptions": { 9 | "project": "tsconfig.json", 10 | "sourceType": "module" 11 | }, 12 | "plugins": ["@typescript-eslint", "jest"], 13 | "extends": [ 14 | "eslint:recommended", 15 | "plugin:@typescript-eslint/eslint-recommended", 16 | "plugin:@typescript-eslint/recommended", 17 | "plugin:jest/recommended", 18 | "prettier" 19 | ], 20 | "rules": {} 21 | } 22 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "module": "commonjs", 5 | "moduleResolution": "node", 6 | "allowSyntheticDefaultImports": true, 7 | "allowJs": true, 8 | "declaration": true, 9 | "importHelpers": true, 10 | "jsx": "react", 11 | "alwaysStrict": true, 12 | "sourceMap": true, 13 | "forceConsistentCasingInFileNames": true, 14 | "noFallthroughCasesInSwitch": true, 15 | "noImplicitReturns": true, 16 | "noUnusedLocals": true, 17 | "noUnusedParameters": true, 18 | "noImplicitAny": false, 19 | "noImplicitThis": false, 20 | "strictNullChecks": false 21 | }, 22 | "include": ["src/**/*", "__tests__/**/*"] 23 | } 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # backo3 2 | 3 | Simple exponential backoff because the others seem to have weird abstractions. 4 | 5 | It's based on [backo2](https://github.com/mokesmokes/backo), The difference is as follows. 6 | 7 | 1. Rewrite with TypeScript 8 | 1. Fixed the bug that duration() might return 0 when called many times with jitter parameters 9 | 10 | ## Installation 11 | 12 | ```bash 13 | $ npm install backo3 14 | ``` 15 | 16 | ## Options 17 | 18 | - `min` initial timeout in milliseconds [100] 19 | - `max` max timeout [10000] 20 | - `jitter` [0] 21 | - `factor` [2] 22 | 23 | ## Example 24 | 25 | ```js 26 | var Backoff = require('backo3'); 27 | var backoff = new Backoff({ min: 100, max: 20000 }); 28 | 29 | setTimeout(function(){ 30 | something.reconnect(); 31 | }, backoff.duration()); 32 | 33 | // later when something works 34 | backoff.reset() 35 | ``` 36 | 37 | ## License 38 | 39 | MIT 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Chris Hager 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /__tests__/main.test.ts: -------------------------------------------------------------------------------- 1 | import Backoff from '../src/Backoff'; 2 | 3 | describe('.duration()', () => { 4 | const min = 100; 5 | const max = 10000; 6 | it('should increase the backoff', () => { 7 | const b = new Backoff({ min, max }); 8 | 9 | expect(b.duration()).toBe(100); 10 | expect(b.duration()).toBe(200); 11 | expect(b.duration()).toBe(400); 12 | expect(b.duration()).toBe(800); 13 | b.reset(); 14 | expect(b.duration()).toBe(100); 15 | expect(b.duration()).toBe(200); 16 | }); 17 | 18 | it('should increase the backoff with jitter', () => { 19 | let i = 0; 20 | const b = new Backoff({ min, max, jitter: 0.5 }); 21 | 22 | while (i < 1e3) { 23 | const d = b.duration(); 24 | const t = 100 * Math.pow(2, i); 25 | if (d === max) { 26 | break; 27 | } 28 | expect(d).toBeGreaterThan(t * 0.5); 29 | expect(d).toBeLessThan(t * 1.5); 30 | i++; 31 | } 32 | }); 33 | 34 | it('should return max after too many invokes with jitter', () => { 35 | const b = new Backoff({ min, max, jitter: 0.5 }); 36 | 37 | for (let i = 0; i < 1e5; i++) { 38 | b.duration(); 39 | } 40 | expect(b.duration()).toBe(max); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /src/Backoff.ts: -------------------------------------------------------------------------------- 1 | export default class Backoff { 2 | private min: number; 3 | private max: number; 4 | private jitter: number; 5 | private factor: number; 6 | private attempts = 0; 7 | 8 | constructor( 9 | options: { 10 | min?: number; 11 | max?: number; 12 | jitter?: number; 13 | factor?: number; 14 | } = {}, 15 | ) { 16 | this.min = options.min || 100; 17 | this.max = options.max || 10000; 18 | this.factor = options.factor || 2; 19 | this.setJitter(options.jitter); 20 | } 21 | 22 | public duration() { 23 | let ms = this.min * Math.pow(this.factor, this.attempts++); 24 | 25 | if (ms === Infinity) { 26 | return this.max; 27 | } 28 | 29 | if (this.jitter) { 30 | const rand = Math.random(); 31 | const deviation = Math.floor(rand * this.jitter * ms); 32 | ms = Math.floor(ms - deviation + 2 * deviation * rand); 33 | } 34 | return Math.min(ms, this.max); 35 | } 36 | 37 | public reset() { 38 | this.attempts = 0; 39 | } 40 | 41 | public setMin(value: number) { 42 | this.min = value; 43 | } 44 | 45 | public setMax(value: number) { 46 | this.max = value; 47 | } 48 | 49 | public setJitter(value: number) { 50 | this.jitter = value > 0 && value <= 1 ? value : 0; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "backo3", 3 | "version": "0.0.2", 4 | "description": "simple backoff based on mokesmokes/backo", 5 | "engines": { 6 | "node": ">= 10" 7 | }, 8 | "files": [ 9 | "build" 10 | ], 11 | "keywords": [ 12 | "backoff" 13 | ], 14 | "types": "build/Backoff.d.ts", 15 | "main": "./build/Backoff.js", 16 | "devDependencies": { 17 | "@types/jest": "~27.0.2", 18 | "@types/node": "~16.11.6", 19 | "@typescript-eslint/eslint-plugin": "~5.3.0", 20 | "@typescript-eslint/parser": "~5.3.0", 21 | "eslint": "~8.1.0", 22 | "eslint-config-prettier": "~8.3.0", 23 | "eslint-plugin-jest": "~25.2.2", 24 | "jest": "~27.3.1", 25 | "prettier": "~2.4.1", 26 | "rimraf": "~3.0.2", 27 | "ts-jest": "~27.0.7", 28 | "tsutils": "~3.21.0", 29 | "typescript": "~4.4.4" 30 | }, 31 | "scripts": { 32 | "start": "node build/src/main.js", 33 | "clean": "rimraf coverage build tmp", 34 | "prebuild": "npm run lint", 35 | "build": "tsc -p tsconfig.release.json", 36 | "build:watch": "tsc -w -p tsconfig.release.json", 37 | "lint": "eslint . --ext .ts,.tsx", 38 | "test": "jest --coverage", 39 | "test:watch": "jest --watch" 40 | }, 41 | "author": "Tom Wan", 42 | "repository": "wanming/backo3", 43 | "license": "MIT", 44 | "dependencies": {} 45 | } 46 | --------------------------------------------------------------------------------