diff --git a/src/jump.js b/src/jump.js index 9e59114..fb13bd0 100644 --- a/src/jump.js +++ b/src/jump.js @@ -23,6 +23,8 @@ const jumper = () => { let callback // to call when done scrolling (function) + let requestID // requestAnimationFrame id (number) + // scroll position helper function location() { @@ -53,9 +55,13 @@ const jumper = () => { window.scrollTo(0, next) // check progress - timeElapsed < duration - ? requestAnimationFrame(loop) // continue scroll loop - : done() // scrolling is done + if (timeElapsed < duration) { + // continue scroll loop + requestID = requestAnimationFrame(loop) + } else { + // scrolling is done + done(); + } } // scroll finished helper @@ -82,6 +88,20 @@ const jumper = () => { timeStart = false } + // cancels the requestAnimationFrame + + function cancel() { + timeStart = false; + + cancelAnimationFrame(requestID); + } + + // indicates whether jumper is executing + + function isJumping() { + return !!timeStart; + } + // API function jump(target, options = {}) { @@ -136,11 +156,17 @@ const jumper = () => { } // start the loop - requestAnimationFrame(loop) + requestID = requestAnimationFrame(loop) + + return cancel } // expose only the jump method - return jump + return { + jump, + cancel, + isJumping, + }; } // export singleton