Skip to content

Feat: Tween delaying #2

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[*]
indent_style = space
indent_size = 2
1 change: 1 addition & 0 deletions docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ <h4 class="mt-4 mb-2 Label bg-blue">API</h4>
<li><code class="text-purple">done</code>: callback function called when tweening is done</li>
<li><code class="text-purple">easeFunc</code>: function used for easing - default: <code class="text-purple">easeInOutQuart</code></li>
<li><code class="text-purple">time</code>: time in ms for the tween - default: <code class="text-purple">400</code></li>
<li><code class="text-purple">delay</code>: time in ms for the tween to be delay - default: <code class="text-purple">0</code></li>
</ul>
<code class="text-purple text-right f5 mr-3">return value</code> <p><code class="text-purple">() =&gt; void</code> - a 'stop' function to stop tweening</p>
</div>
Expand Down
14 changes: 12 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,27 @@ import { easeInOutQuart } from './ease.js'
* @arg {number} [opts.time = 400] - how long the tween should last
* @arg {function} [opts.done] - function called when tweening is finished
* @arg {function} [opts.ease] - function used for easing the tween
* @arg {Number} [opts.delay] - Delays the tweened
* @returns {function} - callback that can stop a tween in progress
*/
export function tween(from, to, cb, { time = 400, done, ease = easeInOutQuart } = {}) {
export function tween(from, to, cb, { time = 400, done, ease = easeInOutQuart, delay=0 } = {}) {
const windowExists = (typeof window !== 'undefined')
let stopped = false
const stop = () => stopped = true
const diff = from - to
let start = null
/**
* Step function
* @arg {Number} timestamp - the time elsaped since the animation started
*/
function step(timestamp) {
if (stopped) return
if (!start) start = timestamp
if (!start) start = (timestamp + delay)
if (start > timestamp) {
window.requestAnimationFrame(step)
return
}

const progress = timestamp - start
const percentage = Math.min(progress / time, 1)
cb(from - ease(percentage) * diff)
Expand Down
Loading