Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Priority Queue: Invoke callback when flushing queue #19282

Merged
merged 8 commits into from
Jan 16, 2020
8 changes: 5 additions & 3 deletions packages/priority-queue/src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/**
* Internal dependencies
*/
import requestIdleCallback from './request-idle-callback';

/**
* Enqueued callback to invoke once idle time permits.
*
Expand Down Expand Up @@ -31,9 +36,6 @@
* @property {WPPriorityQueueFlush} flush Flush queue for context.
*/

/** @type {typeof window.requestIdleCallback|typeof window.requestAnimationFrame} */
const requestIdleCallback = window.requestIdleCallback ? window.requestIdleCallback : window.requestAnimationFrame;

/**
* Creates a context-aware queue that only executes
* the last task of a given context.
Expand Down
14 changes: 14 additions & 0 deletions packages/priority-queue/src/request-idle-callback.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* @return {typeof window.requestIdleCallback|typeof window.requestAnimationFrame|((callback:(timestamp:number)=>void)=>void)}
*/
export function createRequestIdleCallback() {
if ( typeof 'window' === undefined ) {
return ( callback ) => {
setTimeout( () => callback( Date.now() ), 0 );
};
}

return window.requestIdleCallback || window.requestAnimationFrame;
}

export default createRequestIdleCallback();
34 changes: 34 additions & 0 deletions packages/priority-queue/src/test/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* External dependencies
*/
import { EventEmitter } from 'events';

/**
* Internal dependencies
*/
import { createQueue } from '../';
import requestIdleCallback from '../request-idle-callback';

const emitter = new EventEmitter();

const tick = () => emitter.emit( 'tick' );

jest.mock( '../request-idle-callback', () => jest.fn() );

requestIdleCallback.mockImplementation( ( callback ) => {
emitter.once( 'tick', () => callback( Date.now() ) );
} );
aduth marked this conversation as resolved.
Show resolved Hide resolved

describe( 'createQueue', () => {
let queue;
beforeEach( () => {
queue = createQueue();
} );

it( 'runs callback after processing waiting queue', () => {
const callback = jest.fn();
queue.add( {}, callback );
tick();
expect( callback ).toHaveBeenCalled();
aduth marked this conversation as resolved.
Show resolved Hide resolved
} );
} );