Pause and Play Extension for TweenJS

By Stephen Garside on 10/25/2016

Whilst writing a new Guided Tour feature for my online virtual tour website called 360Jungle I found that I needed to extend the excellent TweenJS library to allow me to pause and re-start my tween animations.  I checked around online and could not find any solutions that extended TweenJS so decided to write my own and share it for people in the same predicament.

TweenJS animates using the current time measured against a start time for each tween.  Using these two variables, an elapsed time is calculated so the animation know exactly where it should be against current time.

The first thing I did was to add a couple of variables to the core TWEEN class as follows: 

var _tweens = [];
var _paused = false;
var _lastPauseStartTime;

I then added a couple of public methods to the main TWEEN class to expose a Pause and Play method:-

pause: function ()

{

    _paused = true;

    _lastPauseStartTime = TWEEN.now();

},

 

play: function ()

{

    var totalPausedTime = TWEEN.now() - _lastPauseStartTime;

 

    if (_tweens)

    {

        for (var i = 0; i < _tweens.length; i++)

        {

            _tweens[i].moveStartTimeForward(totalPausedTime);

        }

    }

 

    _paused = false;

}

Next, I added a check to the existing TWEEN.update method to only update tweens if TWEEN is not paused:- 

update: function (time, preserve)

{

    if (!_paused)

    {

        if (_tweens.length === 0)

        {

            return false;

        }

 

        var i = 0;

 

        time = time !== undefined ? time : TWEEN.now();

 

        while (i < _tweens.length)

        {

 

            if (_tweens[i].update(time) || preserve)

            {

                i++;

            } else

            {

                _tweens.splice(i, 1);

            }

 

        }

 

        return true;

    }

    else

    {

        return false;

    }

}

The last piece of the jigsaw is to add a method to each tween object to move the start time forward for any tween that is currently playing:-

this.moveStartTimeForward = function (totalPausedTime)

{

    _startTime = _startTime + totalPausedTime;

};

I hope this helps anybody trying to implement a pause function in TweenJS.  You can see my tweening in action by looking at my virtual guided tour demo at 360Jungle.

Share this article...
Join the Discussion...