Skip to content

Instantly share code, notes, and snippets.

@kayac-chang
Last active September 8, 2019 06:17
Show Gist options
  • Save kayac-chang/f08f84635522827e3ffab7dc05011dea to your computer and use it in GitHub Desktop.
Save kayac-chang/f08f84635522827e3ffab7dc05011dea to your computer and use it in GitHub Desktop.
PressHold: Execute function once at first time. And after 1 second will execute the function on every frames.
/**
* pressHold
* Execute function once at first time.
* And after 1 second will execute the function on every frames.
*
* ** the parameter function must return a Boolean to telling the operation is done. **
*
* Example:
* it = Button();
* it.on('pointerdown', pressHold(onClick, it));
* function onClick() { *** }
*
* @param {Function} func - The function want to execute when long press, must return a Boolean.
* @param {EventEmitter} it - The element which be pressed.
* @return {call}
*/
function pressHold(func, it) {
//
return function call() {
let holding = true;
it.once('pointerup', () => holding = false);
let done = func();
(
async function execute(getDuration) {
const duration = getDuration();
if (duration > 1000) done = func();
if (done || !holding) return;
await nextFrame();
return execute(getDuration);
}
)(Timer());
};
}
function Timer() {
const start = performance.now();
return function get() {
return performance.now() - start;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment