UNPKG

simple-in-memory-queue

Version:

A simple in-memory queue, for nodejs and the browser, with consumers for common usecases.

52 lines 2.78 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createQueueWithDebounceConsumer = void 0; const constants_1 = require("../../domain/constants"); const createQueue_1 = require("../queue/createQueue"); /** * creates a queue with a consumer that consumes all items from it as soon as new items stop being added * * note * - produces one call to the consumer for all pushes to the queue that occurred within the delay period of eachother * * usecases * - waiting until all rapid activity stops to summarize the activity, before processing it * - for example: scroll events, mouse movements, typing, etc */ const createQueueWithDebounceConsumer = ({ consumer, gap, }) => { // create the queue const queue = (0, createQueue_1.createQueue)({ order: constants_1.QueueOrder.FIRST_IN_FIRST_OUT }); // subscribe to the queue, calling the consumer, with debouncing let priorTimeoutHandle = null; queue.on.push.subscribe({ consumer: () => { // if a timeout already exists, remove it if (priorTimeoutHandle) clearTimeout(priorTimeoutHandle); // set a new timeout of 100ms to capture the screen changes priorTimeoutHandle = setTimeout(() => __awaiter(void 0, void 0, void 0, function* () { // define the current length of the queue const length = queue.length + 0; // +0 to ensure its a copy, and not a reference // grab all of the items currently from the queue, without removing them from the queue yet const items = queue.peek(length); // wait for the consumer to successfully process the items yield consumer({ items }); // dequeue the items from the queue, now that they're all processed queue.pop(length); }), gap.milliseconds); }, }); // return the queue return queue; }; exports.createQueueWithDebounceConsumer = createQueueWithDebounceConsumer; //# sourceMappingURL=createQueueWithDebounceConsumer.js.map