├── lock.js ├── package.json └── README.md /lock.js: -------------------------------------------------------------------------------- 1 | window.Rd = window.Rd || {} 2 | 3 | window.Rd.lock = function (asyncFunction) { 4 | var ready = true 5 | 6 | return function (callback) { 7 | if (ready) { 8 | ready = false 9 | asyncFunction(function () { 10 | callback() 11 | ready = true 12 | }) 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@readable/lock", 3 | "version": "0.0.1", 4 | "description": "Create a function that can only be executed sequentially", 5 | "main": "lock.js", 6 | "scripts": { 7 | "lint": "standard lock.js README.md", 8 | "preversion": "npm run lint" 9 | }, 10 | "keywords": [ 11 | "binary", 12 | "lock", 13 | "mutex", 14 | "semaphore", 15 | "sync", 16 | "synchronization" 17 | ], 18 | "author": "Oleg", 19 | "license": "MIT", 20 | "devDependencies": { 21 | "eslint-plugin-markdown": "^1.0.0-beta.4", 22 | "standard": "^9.0.2" 23 | }, 24 | "standard": { 25 | "envs": [ 26 | "browser" 27 | ], 28 | "globals": [ 29 | "Rd" 30 | ], 31 | "plugins": [ 32 | "markdown" 33 | ] 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Standard - JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) 2 | 3 | # Lock 4 | 5 | Tool to create a trailing edge throttle out of any deferring function. 6 | 7 | Places a lock on a function preventing its simultaneous execution. 8 | While another execution is due, all other requests to run will be ignored. 9 | 10 | ``` js 11 | var throttle = Rd.lock(function (callback) { 12 | setTimeout(callback, 16) 13 | }) 14 | 15 | window.addEventListener('resize', function () { 16 | throttle(function () { 17 | // Update DOM no more than every 16ms (~ 60fps) 18 | }) 19 | }) 20 | 21 | ``` 22 | 23 | ``` js 24 | var throttledRAF = Rd.lock(requestAnimationFrame) 25 | 26 | window.addEventListener('resize', function () { 27 | throttledRAF(function () { 28 | // Update DOM before repaint 29 | }) 30 | }) 31 | ``` 32 | --------------------------------------------------------------------------------