├── .gitignore ├── .husky ├── commit-msg └── pre-commit ├── src ├── types │ ├── timer-type.ts │ ├── function-map.ts │ └── index.ts ├── tsconfig.json ├── factories │ ├── clear-function.ts │ ├── call-function.ts │ └── schedule-function.ts └── module.ts ├── config ├── tslint │ └── src.json ├── lint-staged │ └── config.json ├── vitest │ ├── unit-setup.ts │ ├── unit.ts │ └── integration.ts ├── eslint │ ├── src.json │ ├── config.json │ └── test.json ├── prettier │ └── config.json ├── babel │ ├── build.json │ └── test.json └── rollup │ └── bundle.mjs ├── test ├── unit │ └── factories │ │ ├── clear-function.js │ │ └── call-function.js └── integration │ └── module.js ├── LICENSE ├── .github └── workflows │ └── test.yml ├── README.md └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | node_modules/ 3 | /build/ 4 | -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | commitlint --edit --extends @commitlint/config-angular 2 | -------------------------------------------------------------------------------- /src/types/timer-type.ts: -------------------------------------------------------------------------------- 1 | export type TTimerType = 'interval' | 'timeout'; 2 | -------------------------------------------------------------------------------- /config/tslint/src.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint-config-holy-grail" 3 | } 4 | -------------------------------------------------------------------------------- /src/types/function-map.ts: -------------------------------------------------------------------------------- 1 | export type TFunctionMap = Map; 2 | -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from './function-map'; 2 | export * from './timer-type'; 3 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | lint-staged --config config/lint-staged/config.json && npm run lint 2 | -------------------------------------------------------------------------------- /config/lint-staged/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "*": "prettier --config config/prettier/config.json --ignore-unknown --write" 3 | } 4 | -------------------------------------------------------------------------------- /config/vitest/unit-setup.ts: -------------------------------------------------------------------------------- 1 | import { use } from 'chai'; 2 | import sinonChai from 'sinon-chai'; 3 | 4 | use(sinonChai); 5 | -------------------------------------------------------------------------------- /config/eslint/src.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true 4 | }, 5 | "extends": "eslint-config-holy-grail" 6 | } 7 | -------------------------------------------------------------------------------- /src/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "isolatedModules": true 4 | }, 5 | "extends": "tsconfig-holy-grail/src/tsconfig-browser" 6 | } 7 | -------------------------------------------------------------------------------- /src/factories/clear-function.ts: -------------------------------------------------------------------------------- 1 | import { TFunctionMap } from '../types'; 2 | 3 | export const createClearFunction = (functions: TFunctionMap) => (id: number) => { 4 | functions.delete(id); 5 | }; 6 | -------------------------------------------------------------------------------- /config/prettier/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "always", 3 | "printWidth": 140, 4 | "quoteProps": "consistent", 5 | "singleQuote": true, 6 | "tabWidth": 4, 7 | "trailingComma": "none" 8 | } 9 | -------------------------------------------------------------------------------- /config/eslint/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "node": true 4 | }, 5 | "extends": "eslint-config-holy-grail", 6 | "rules": { 7 | "no-sync": "off", 8 | "node/no-missing-require": "off" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /config/babel/build.json: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "targets": { 7 | "node": "20.9" 8 | } 9 | } 10 | ] 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /config/babel/test.json: -------------------------------------------------------------------------------- 1 | { 2 | "only": ["./test"], 3 | "presets": [ 4 | [ 5 | "@babel/preset-env", 6 | { 7 | "targets": { 8 | "node": "20.9" 9 | } 10 | } 11 | ] 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /config/eslint/test.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "mocha": true 5 | }, 6 | "extends": "eslint-config-holy-grail", 7 | "globals": { 8 | "expect": "readonly" 9 | }, 10 | "rules": { 11 | "no-unused-expressions": "off", 12 | "node/file-extension-in-import": "off", 13 | "node/no-missing-require": "off" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/factories/call-function.ts: -------------------------------------------------------------------------------- 1 | import { TFunctionMap, TTimerType } from '../types'; 2 | 3 | export const createCallFunction = (functions: TFunctionMap, type: TTimerType) => (id: number) => { 4 | if (functions.has(id)) { 5 | const func = functions.get(id); 6 | 7 | if (func !== undefined) { 8 | func(); 9 | 10 | if (type === 'timeout') { 11 | functions.delete(id); 12 | } 13 | } 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /test/unit/factories/clear-function.js: -------------------------------------------------------------------------------- 1 | import { beforeEach, describe, expect, it } from 'vitest'; 2 | import { createClearFunction } from '../../../src/factories/clear-function'; 3 | 4 | describe('clearFunction()', () => { 5 | let clearFunction; 6 | let functions; 7 | let id; 8 | 9 | beforeEach(() => { 10 | id = 17; 11 | functions = new Map([[id, () => {}]]); 12 | 13 | clearFunction = createClearFunction(functions); 14 | }); 15 | 16 | it('should delete the function with the given id', () => { 17 | clearFunction(id); 18 | 19 | expect(functions.has(id)).to.be.false; 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /config/rollup/bundle.mjs: -------------------------------------------------------------------------------- 1 | import babel from '@rollup/plugin-babel'; 2 | 3 | // eslint-disable-next-line import/no-default-export 4 | export default { 5 | input: 'build/es2019/module.js', 6 | output: { 7 | file: 'build/es5/bundle.js', 8 | format: 'umd', 9 | name: 'audioContextTimers' 10 | }, 11 | plugins: [ 12 | babel({ 13 | babelHelpers: 'runtime', 14 | exclude: 'node_modules/**', 15 | plugins: ['@babel/plugin-external-helpers', '@babel/plugin-transform-runtime'], 16 | presets: [ 17 | [ 18 | '@babel/preset-env', 19 | { 20 | modules: false 21 | } 22 | ] 23 | ] 24 | }) 25 | ] 26 | }; 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Christoph Guttandin 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. 22 | -------------------------------------------------------------------------------- /test/unit/factories/call-function.js: -------------------------------------------------------------------------------- 1 | import { beforeEach, describe, expect, it } from 'vitest'; 2 | import { createCallFunction } from '../../../src/factories/call-function'; 3 | import { spy } from 'sinon'; 4 | 5 | describe('callFunction()', () => { 6 | let func; 7 | let functions; 8 | let id; 9 | 10 | beforeEach(() => { 11 | func = spy(); 12 | id = 17; 13 | functions = new Map([[id, func]]); 14 | }); 15 | 16 | describe('with a timer of type interval', () => { 17 | let callFunction; 18 | 19 | beforeEach(() => { 20 | callFunction = createCallFunction(functions, 'interval'); 21 | }); 22 | 23 | it('should call the function with the given id', () => { 24 | callFunction(id); 25 | 26 | expect(func).to.have.been.calledOnce; 27 | }); 28 | 29 | it('should not delete the function with the given id', () => { 30 | callFunction(id); 31 | 32 | expect(functions.has(id)).to.be.true; 33 | }); 34 | }); 35 | 36 | describe('with a timer of type timeout', () => { 37 | let callFunction; 38 | 39 | beforeEach(() => { 40 | callFunction = createCallFunction(functions, 'timeout'); 41 | }); 42 | 43 | it('should call the function with the given id', () => { 44 | callFunction(id); 45 | 46 | expect(func).to.have.been.calledOnce; 47 | }); 48 | 49 | it('should delete the function with the given id', () => { 50 | callFunction(id); 51 | 52 | expect(functions.has(id)).to.be.false; 53 | }); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | build: 13 | runs-on: ${{ (matrix.target == 'firefox' && matrix.type == 'integration') && 'macos-latest' || 'ubuntu-latest' }} 14 | 15 | strategy: 16 | matrix: 17 | include: 18 | - node-version: 20.x 19 | target: node 20 | type: integration 21 | node-version: [20.x] 22 | target: [chrome, firefox] 23 | type: [integration, unit] 24 | max-parallel: 3 25 | 26 | steps: 27 | - name: Checkout repository 28 | uses: actions/checkout@v6 29 | 30 | - name: Install Node.js ${{ matrix.node-version }} 31 | uses: actions/setup-node@v6 32 | with: 33 | node-version: ${{ matrix.node-version }} 34 | 35 | - name: Cache node modules 36 | uses: actions/cache@v5 37 | with: 38 | path: ~/.npm 39 | key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} 40 | restore-keys: | 41 | ${{ runner.os }}-node- 42 | 43 | - name: Install dependencies 44 | run: npm ci 45 | 46 | - env: 47 | BROWSER_STACK_ACCESS_KEY: ${{ secrets.BROWSER_STACK_ACCESS_KEY }} 48 | BROWSER_STACK_USERNAME: ${{ secrets.BROWSER_STACK_USERNAME }} 49 | TARGET: ${{ matrix.target }} 50 | TYPE: ${{ matrix.type }} 51 | name: Run ${{ matrix.type }} tests 52 | run: npm test 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # audio-context-timers 2 | 3 | **A replacement for setInterval() and setTimeout() which works in unfocused windows.** 4 | 5 | [![version](https://img.shields.io/npm/v/audio-context-timers.svg?style=flat-square)](https://www.npmjs.com/package/audio-context-timers) 6 | 7 | ## Motivation 8 | 9 | For scripts that rely on [WindowTimers](http://www.w3.org/TR/html5/webappapis.html#timers) like setInterval() or setTimeout() things get confusing when the site which the script is running on loses focus. Chrome, Firefox and maybe others throttle the frequency at which they invoke those timers to a maximum of once per second in such a situation. However it is possible to schedule [AudioBufferSourceNodes](https://webaudio.github.io/web-audio-api/#AudioBufferSourceNode) and listen for their [`onended`](https://webaudio.github.io/web-audio-api/#widl-AudioScheduledSourceNode-onended) event to achieve a similar result. This makes it possible to avoid the throttling. 10 | 11 | ## Getting Started 12 | 13 | `audio-context-timers` is available as a package on [npm](https://www.npmjs.org/package/audio-context-timers). Run the following command to install it: 14 | 15 | ```shell 16 | npm install audio-context-timers 17 | ``` 18 | 19 | You can then import the exported functions in your code like this: 20 | 21 | ```js 22 | import { clearInterval, clearTimeout, setInterval, setTimeout } from 'audio-context-timers'; 23 | ``` 24 | 25 | The usage is exactly the same as with the corresponding functions on the global scope. 26 | 27 | ```js 28 | var intervalId = setInterval(() => { 29 | // do something many times 30 | }, 100); 31 | 32 | clearInterval(intervalId); 33 | 34 | var timeoutId = setTimeout(() => { 35 | // do something once 36 | }, 100); 37 | 38 | clearTimeout(timeoutId); 39 | ``` 40 | 41 | However there are some subtle differences between `audio-context-timers` and WindowTimers which are the same those of the [`worker-timers`](https://github.com/chrisguttandin/worker-timers) package. 42 | -------------------------------------------------------------------------------- /src/factories/schedule-function.ts: -------------------------------------------------------------------------------- 1 | import type { IAudioBuffer, IAudioBufferSourceNode, IMinimalAudioContext } from 'standardized-audio-context'; 2 | import { TTimerType } from '../types'; 3 | import type { createCallFunction } from './call-function'; 4 | 5 | export const createScheduleFunction = ( 6 | callFunction: ReturnType, 7 | createAudioBuffer: (length: number, sampleRate: number) => IAudioBuffer, 8 | createAudioBufferSourceNode: ( 9 | minimalAudioContext: ReturnType, 10 | audioBuffer: ReturnType 11 | ) => IAudioBufferSourceNode, 12 | createMinimalAudioContext: () => IMinimalAudioContext, 13 | performance: Pick 14 | ) => { 15 | let audioBuffer: null | ReturnType = null; 16 | let minimalAudioContext: null | ReturnType = null; 17 | 18 | const scheduleFunction = (id: number, delay: number, type: TTimerType) => { 19 | const now = performance.now(); 20 | 21 | if (minimalAudioContext === null) { 22 | minimalAudioContext = createMinimalAudioContext(); 23 | } 24 | 25 | const { destination, sampleRate } = minimalAudioContext; 26 | 27 | if (audioBuffer === null) { 28 | audioBuffer = createAudioBuffer(2, sampleRate); 29 | } 30 | 31 | const audioBufferSourceNode = createAudioBufferSourceNode(minimalAudioContext, audioBuffer); 32 | 33 | audioBufferSourceNode.onended = () => { 34 | const elapsedTime = performance.now() - now; 35 | 36 | if (elapsedTime >= delay) { 37 | callFunction(id); 38 | } else { 39 | scheduleFunction(id, delay - elapsedTime, type); 40 | } 41 | 42 | audioBufferSourceNode.disconnect(destination); 43 | }; 44 | 45 | audioBufferSourceNode.connect(destination); 46 | audioBufferSourceNode.start(Math.max(0, minimalAudioContext.currentTime + delay / 1000 - audioBuffer.duration)); 47 | }; 48 | 49 | return scheduleFunction; 50 | }; 51 | -------------------------------------------------------------------------------- /src/module.ts: -------------------------------------------------------------------------------- 1 | import { generateUniqueNumber } from 'fast-unique-numbers'; 2 | import { 3 | AudioBuffer, 4 | AudioBufferSourceNode, 5 | IAudioBuffer, 6 | IMinimalAudioContext, 7 | MinimalAudioContext, 8 | isSupported 9 | } from 'standardized-audio-context'; 10 | import { createCallFunction } from './factories/call-function'; 11 | import { createClearFunction } from './factories/clear-function'; 12 | import { createScheduleFunction } from './factories/schedule-function'; 13 | import { TFunctionMap } from './types'; 14 | 15 | const SCHEDULED_INTERVAL_FUNCTIONS: TFunctionMap = new Map(); 16 | const callIntervalFunction = createCallFunction(SCHEDULED_INTERVAL_FUNCTIONS, 'interval'); 17 | 18 | export const clearInterval = createClearFunction(SCHEDULED_INTERVAL_FUNCTIONS); 19 | 20 | const SCHEDULED_TIMEOUT_FUNCTIONS: TFunctionMap = new Map(); 21 | const callTimeoutFunction = createCallFunction(SCHEDULED_TIMEOUT_FUNCTIONS, 'timeout'); 22 | 23 | export const clearTimeout = createClearFunction(SCHEDULED_TIMEOUT_FUNCTIONS); 24 | 25 | export { isSupported }; 26 | 27 | const createAudioBuffer = (length: number, sampleRate: number) => new AudioBuffer({ length, sampleRate }); 28 | const createAudioBufferSourceNode = (minimalAudioContext: IMinimalAudioContext, audioBuffer: IAudioBuffer) => 29 | new AudioBufferSourceNode(minimalAudioContext, { buffer: audioBuffer }); 30 | const createMinimalAudioContext = () => new MinimalAudioContext(); 31 | const scheduleIntervalFunction = createScheduleFunction( 32 | callIntervalFunction, 33 | createAudioBuffer, 34 | createAudioBufferSourceNode, 35 | createMinimalAudioContext, 36 | performance 37 | ); 38 | 39 | export const setInterval = (func: Function, delay: number) => { 40 | const id = generateUniqueNumber(SCHEDULED_INTERVAL_FUNCTIONS); 41 | 42 | SCHEDULED_INTERVAL_FUNCTIONS.set(id, () => { 43 | func(); 44 | 45 | scheduleIntervalFunction(id, delay, 'interval'); 46 | }); 47 | 48 | scheduleIntervalFunction(id, delay, 'interval'); 49 | 50 | return id; 51 | }; 52 | 53 | const scheduleTimeoutFunction = createScheduleFunction( 54 | callTimeoutFunction, 55 | createAudioBuffer, 56 | createAudioBufferSourceNode, 57 | createMinimalAudioContext, 58 | performance 59 | ); 60 | 61 | export const setTimeout = (func: Function, delay: number) => { 62 | const id = generateUniqueNumber(SCHEDULED_TIMEOUT_FUNCTIONS); 63 | 64 | SCHEDULED_TIMEOUT_FUNCTIONS.set(id, func); 65 | 66 | scheduleTimeoutFunction(id, delay, 'timeout'); 67 | 68 | return id; 69 | }; 70 | -------------------------------------------------------------------------------- /config/vitest/unit.ts: -------------------------------------------------------------------------------- 1 | import { env } from 'node:process'; 2 | import { webdriverio } from '@vitest/browser-webdriverio'; 3 | import { defineConfig } from 'vitest/config'; 4 | 5 | export default defineConfig({ 6 | test: { 7 | watch: false, 8 | browser: { 9 | enabled: true, 10 | instances: env.CI 11 | ? env.TARGET === 'chrome' 12 | ? [{ browser: 'chrome', name: 'Chrome', provider: webdriverio() }] 13 | : env.TARGET === 'firefox' 14 | ? [{ browser: 'firefox', name: 'Firefox', provider: webdriverio() }] 15 | : [] 16 | : [ 17 | { 18 | browser: 'chrome', 19 | name: 'Chrome', 20 | provider: webdriverio({ 21 | capabilities: { 22 | 'goog:chromeOptions': { 23 | args: ['--headless'] 24 | } 25 | } 26 | }) 27 | }, 28 | { 29 | browser: 'chrome', 30 | name: 'Chrome Canary', 31 | provider: webdriverio({ 32 | capabilities: { 33 | 'goog:chromeOptions': { 34 | args: ['--headless'], 35 | binary: '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary' 36 | } 37 | } 38 | }) 39 | }, 40 | { 41 | name: 'Firefox Developer', 42 | browser: 'firefox', 43 | provider: webdriverio({ 44 | capabilities: { 45 | 'moz:firefoxOptions': { 46 | args: ['-headless'], 47 | binary: '/Applications/Firefox\ Developer\ Edition.app/Contents/MacOS/firefox' 48 | } 49 | } 50 | }) 51 | }, 52 | { 53 | browser: 'firefox', 54 | name: 'Firefox', 55 | provider: webdriverio({ 56 | capabilities: { 57 | 'moz:firefoxOptions': { 58 | args: ['-headless'] 59 | } 60 | } 61 | }) 62 | }, 63 | { browser: 'safari', name: 'Safari', provider: webdriverio() } 64 | ] 65 | }, 66 | dir: 'test/unit/', 67 | include: ['**/*.js'], 68 | setupFiles: ['config/vitest/unit-setup.ts'] 69 | } 70 | }); 71 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Christoph Guttandin", 3 | "bugs": { 4 | "url": "https://github.com/chrisguttandin/audio-context-timers/issues" 5 | }, 6 | "config": { 7 | "commitizen": { 8 | "path": "cz-conventional-changelog" 9 | } 10 | }, 11 | "dependencies": { 12 | "@babel/runtime": "^7.28.4", 13 | "fast-unique-numbers": "^9.0.24", 14 | "standardized-audio-context": "^25.3.77", 15 | "tslib": "^2.8.1" 16 | }, 17 | "description": "A replacement for setInterval() and setTimeout() which works in unfocused windows.", 18 | "devDependencies": { 19 | "@babel/cli": "^7.28.3", 20 | "@babel/core": "^7.28.5", 21 | "@babel/plugin-external-helpers": "^7.27.1", 22 | "@babel/plugin-transform-runtime": "^7.28.5", 23 | "@babel/preset-env": "^7.28.5", 24 | "@commitlint/cli": "^19.8.1", 25 | "@commitlint/config-angular": "^19.8.1", 26 | "@rollup/plugin-babel": "^6.1.0", 27 | "@vitest/browser-webdriverio": "^4.0.16", 28 | "chai": "^6.2.1", 29 | "commitizen": "^4.3.1", 30 | "cz-conventional-changelog": "^3.3.0", 31 | "eslint": "^8.57.0", 32 | "eslint-config-holy-grail": "^61.0.3", 33 | "husky": "^9.1.7", 34 | "lint-staged": "^16.2.7", 35 | "prettier": "^3.7.4", 36 | "rimraf": "^6.1.2", 37 | "rollup": "^4.54.0", 38 | "sinon": "^21.0.1", 39 | "sinon-chai": "^4.0.1", 40 | "tsconfig-holy-grail": "^15.0.2", 41 | "tslint": "^6.1.3", 42 | "tslint-config-holy-grail": "^56.0.6", 43 | "typescript": "^5.9.3", 44 | "vitest": "^4.0.16" 45 | }, 46 | "files": [ 47 | "build/es2019/", 48 | "build/es5/", 49 | "src/" 50 | ], 51 | "homepage": "https://github.com/chrisguttandin/audio-context-timers", 52 | "keywords": [ 53 | "Web Audio API", 54 | "WindowTimers", 55 | "clearInterval", 56 | "clearTimeout", 57 | "interval", 58 | "setInterval", 59 | "setTimeout" 60 | ], 61 | "license": "MIT", 62 | "main": "build/es5/bundle.js", 63 | "module": "build/es2019/module.js", 64 | "name": "audio-context-timers", 65 | "repository": { 66 | "type": "git", 67 | "url": "https://github.com/chrisguttandin/audio-context-timers.git" 68 | }, 69 | "scripts": { 70 | "build": "rimraf build/* && tsc --project src/tsconfig.json && rollup --config config/rollup/bundle.mjs && babel ./build/es2019 --config-file ./config/babel/build.json --out-dir ./build/node", 71 | "lint": "npm run lint:config && npm run lint:src && npm run lint:test", 72 | "lint:config": "eslint --config config/eslint/config.json --ext .cjs --ext .js --ext .mjs --report-unused-disable-directives config/", 73 | "lint:src": "tslint --config config/tslint/src.json --project src/tsconfig.json src/*.ts src/**/*.ts", 74 | "lint:test": "eslint --config config/eslint/test.json --ext .js --report-unused-disable-directives test/", 75 | "prepare": "husky", 76 | "prepublishOnly": "npm run build", 77 | "test": "npm run lint && npm run build && npm run test:integration-browser && npm run test:integration-node && npm run test:unit", 78 | "test:integration-browser": "if [ \"$TYPE\" = \"\" -o \"$TYPE\" = \"integration\" ] && [ \"$TARGET\" = \"\" -o \"$TARGET\" = \"chrome\" -o \"$TARGET\" = \"firefox\" -o \"$TARGET\" = \"safari\" ]; then npx vitest --config config/vitest/integration.ts; fi", 79 | "test:integration-node": "if [ \"$TYPE\" = \"\" -o \"$TYPE\" = \"integration\" ] && [ \"$TARGET\" = \"\" -o \"$TARGET\" = \"node\" ]; then npx vitest --browser.enabled false --config config/vitest/integration.ts; fi", 80 | "test:unit": "if [ \"$TYPE\" = \"\" -o \"$TYPE\" = \"unit\" ]; then npx vitest --config config/vitest/unit.ts; fi" 81 | }, 82 | "types": "build/es2019/module.d.ts", 83 | "version": "5.0.133" 84 | } 85 | -------------------------------------------------------------------------------- /config/vitest/integration.ts: -------------------------------------------------------------------------------- 1 | import { env } from 'node:process'; 2 | import { webdriverio } from '@vitest/browser-webdriverio'; 3 | import { defineConfig } from 'vitest/config'; 4 | 5 | export default defineConfig({ 6 | test: { 7 | watch: false, 8 | browser: { 9 | enabled: true, 10 | instances: env.CI 11 | ? env.TARGET === 'chrome' 12 | ? [ 13 | { 14 | browser: 'chrome', 15 | name: 'Chrome', 16 | provider: webdriverio({ 17 | capabilities: { 'goog:chromeOptions': { args: ['--autoplay-policy=no-user-gesture-required'] } } 18 | }) 19 | } 20 | ] 21 | : env.TARGET === 'firefox' 22 | ? [ 23 | { 24 | browser: 'firefox', 25 | name: 'Firefox', 26 | provider: webdriverio({ 27 | capabilities: { 'moz:firefoxOptions': { prefs: { 'media.autoplay.default': 0 } } } 28 | }) 29 | } 30 | ] 31 | : [] 32 | : [ 33 | { 34 | browser: 'chrome', 35 | name: 'Chrome', 36 | provider: webdriverio({ 37 | capabilities: { 38 | 'goog:chromeOptions': { 39 | args: ['--autoplay-policy=no-user-gesture-required', '--headless'] 40 | } 41 | } 42 | }) 43 | }, 44 | { 45 | browser: 'chrome', 46 | name: 'Chrome Canary', 47 | provider: webdriverio({ 48 | capabilities: { 49 | 'goog:chromeOptions': { 50 | args: ['--autoplay-policy=no-user-gesture-required', '--headless'], 51 | binary: '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary' 52 | } 53 | } 54 | }) 55 | }, 56 | { 57 | name: 'Firefox Developer', 58 | browser: 'firefox', 59 | provider: webdriverio({ 60 | capabilities: { 61 | 'moz:firefoxOptions': { 62 | args: ['-headless'], 63 | prefs: { 'media.autoplay.default': 0 }, 64 | binary: '/Applications/Firefox\ Developer\ Edition.app/Contents/MacOS/firefox' 65 | } 66 | } 67 | }) 68 | }, 69 | { 70 | browser: 'firefox', 71 | name: 'Firefox', 72 | provider: webdriverio({ 73 | capabilities: { 74 | 'moz:firefoxOptions': { 75 | args: ['-headless'], 76 | prefs: { 'media.autoplay.default': 0 } 77 | } 78 | } 79 | }) 80 | }, 81 | // @ts-expect-error 82 | { browser: 'safari', name: 'Safari', provider: webdriverio({ capabilities: { 'webkit:alwaysAllowAutoplay': true } }) } 83 | ] 84 | }, 85 | dir: 'test/integration/', 86 | include: ['**/*.js'] 87 | } 88 | }); 89 | -------------------------------------------------------------------------------- /test/integration/module.js: -------------------------------------------------------------------------------- 1 | import { afterEach, describe, expect, it } from 'vitest'; 2 | import { clearInterval, clearTimeout, setInterval, setTimeout } from '../../src/module'; 3 | 4 | describe('module', () => { 5 | describe('clearInterval()', () => { 6 | it('should be a function', () => { 7 | expect(clearInterval).to.be.a('function'); 8 | }); 9 | 10 | if (typeof window !== 'undefined') { 11 | it('should not call the function after clearing the interval', () => { 12 | const { promise, resolve } = Promise.withResolvers(); 13 | const id = setInterval(() => { 14 | throw new Error('this should never be called'); 15 | }, 100); 16 | 17 | clearInterval(id); 18 | 19 | // Wait 200ms to be sure the function never gets called. 20 | window.setTimeout(resolve, 200); 21 | 22 | return promise; 23 | }); 24 | 25 | it('should not call the function anymore after clearing the interval after the first callback', () => { 26 | const { promise, resolve } = Promise.withResolvers(); 27 | 28 | let id = setInterval(() => { 29 | if (id === null) { 30 | throw new Error('this should never be called'); 31 | } 32 | 33 | clearInterval(id); 34 | id = null; 35 | }, 50); 36 | 37 | // Wait 200ms to be sure the function gets not called anymore. 38 | window.setTimeout(resolve, 200); 39 | 40 | return promise; 41 | }); 42 | } 43 | }); 44 | 45 | describe('clearTimeout()', () => { 46 | it('should be a function', () => { 47 | expect(clearTimeout).to.be.a('function'); 48 | }); 49 | 50 | if (typeof window !== 'undefined') { 51 | it('should not call the function after clearing the timeout', () => { 52 | const { promise, resolve } = Promise.withResolvers(); 53 | const id = setTimeout(() => { 54 | throw new Error('this should never be called'); 55 | }, 100); 56 | 57 | clearTimeout(id); 58 | 59 | // Wait 200ms to be sure the function never gets called. 60 | window.setTimeout(resolve, 200); 61 | 62 | return promise; 63 | }); 64 | } 65 | }); 66 | 67 | describe('setInterval()', () => { 68 | it('should be a function', () => { 69 | expect(setInterval).to.be.a('function'); 70 | }); 71 | 72 | if (typeof window !== 'undefined') { 73 | let id; 74 | 75 | afterEach(() => { 76 | clearTimeout(id); 77 | }); 78 | 79 | it('should return a numeric id', () => { 80 | id = setInterval(() => {}, 0); 81 | 82 | expect(id).to.be.a('number'); 83 | }); 84 | 85 | it('should constantly call a function with the given delay', () => { 86 | const { promise, resolve } = Promise.withResolvers(); 87 | 88 | let before = performance.now(); 89 | let calls = 0; 90 | 91 | function func() { 92 | const now = performance.now(); 93 | const elapsed = now - before; 94 | 95 | expect(elapsed).to.be.at.least(100); 96 | 97 | // Test five calls. 98 | if (calls > 4) { 99 | resolve(); 100 | } 101 | 102 | before = now; 103 | calls += 1; 104 | } 105 | 106 | id = setInterval(func, 100); 107 | 108 | return promise; 109 | }); 110 | } 111 | }); 112 | 113 | describe('setTimeout()', () => { 114 | it('should be a function', () => { 115 | expect(setTimeout).to.be.a('function'); 116 | }); 117 | 118 | if (typeof window !== 'undefined') { 119 | let id; 120 | 121 | afterEach(() => { 122 | clearInterval(id); 123 | }); 124 | 125 | it('should return a numeric id', () => { 126 | id = setTimeout(() => {}, 0); 127 | 128 | expect(id).to.be.a('number'); 129 | }); 130 | 131 | it('should postpone a function for the given delay', () => { 132 | const { promise, resolve } = Promise.withResolvers(); 133 | const before = performance.now(); 134 | 135 | function func() { 136 | const elapsed = performance.now() - before; 137 | 138 | expect(elapsed).to.be.at.least(100); 139 | 140 | resolve(); 141 | } 142 | 143 | id = setTimeout(func, 100); 144 | 145 | return promise; 146 | }); 147 | } 148 | }); 149 | }); 150 | --------------------------------------------------------------------------------