开发者

Ease-out Using setTimeout

开发者 https://www.devze.com 2023-02-08 00:28 出处:网络
I am attempting to create a slot machine type animation in which a list of emails will be cycled through. I would like the animation to start off 开发者_开发知识库fast but get progressively slower and

I am attempting to create a slot machine type animation in which a list of emails will be cycled through. I would like the animation to start off 开发者_开发知识库fast but get progressively slower and slower until it stops. How would you recommend that I do something like this? I am currently doing something like:

$(function(){

  wait = 1;
  threshold = 100;
  timer = setTimeout(swap_email,wait);

});

function swap_email() {

  wait = wait + 1;

  if(threshold <= wait) {

    // Update the email div....
    timer = setTimeout(swap_email, wait);   

  }

  else {

    // We're done!        

  }

}


Easing/tweening is a function of time. You tell your function how much time has passed, and it tells you how much distance has been traveled.

I use the following equation for 99% of the JS animation I do:

function simple_easing(how_much_time_has_passed) {
    return (1 - Math.cos(how_much_time_has_passed * Math.PI)) / 2;
}

I don't know why it works. I didn't try to understand the mathematics behind it.

But the above equation makes a lot of assumptions about how you're animating. The how_much_time_has_passed argument needs to be a decimal between 0 and 1; it also returns a decimal between 0 and 1, which is pretty much useless on its own (unless you're animating opacity).

When this function returns the how_much value, you'll need to do this to it:

current_value = start_value + total_distance * how_much;

...Which means that you'd have to start keeping track of other stuff that wasn't in your original example.

Further Reading

Robert Penner's awesome chapter about tweening equations from his awesome book.


EDIT: Or, you could just use a jQuery plugin.


Maybe its help you:

var Timer = {
  threshold: 5000,
  wait: 1000,

  Start: function () {
    var _this = this;
    setTimeout(function () { _this.Swap(); }, _this.wait);
  },

  Swap: function () {
    this.wait += 1000;
    if (this.threshold > this.wait) {
      alert('next');
      this.Start();
    } else {
      alert('stop');
    }
  }
};


Use the jQuery easing plugin and all the heavy lifting has been done for you in a single include ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号