如何创建快速然后逐渐减慢的间隔?

时间:2019-01-04 13:13:41

标签: javascript

我正在尝试创建一个间隔,在该间隔中颜色将快速闪烁,然后逐渐减慢直至完全停止。现在我的代码是我现在不了解的东西的一大杂乱。

我的代码实际上只是试图设置一个变化时间的超时。我尝试了一个演示字母的小演示,然后设置了超时以再次自行运行,但是每次都增加超时,从而创建指数的字母曲线。但它并没有停止。

https://jsfiddle.net/eslota52/a6jg1Loh/ (代码太长) 尝试查看addTimeout();函数和doThat();函数的结尾,以寻求帮助。


var colord = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
var colorCode_1;
var colorCode_2;
var colorCode_3;
var colorCode_4;
var colorCode_5;
var colorCode_6;
var finalColor;
var finalColorHex;
var timex;
var interval;
interval = setInterval(doThat, 100);

function doThat() {
  timex = timex + 50;
  colorCode_1 = colord[Math.trunc(Math.random() * colord.length)];
  colorCode_2 = colord[Math.trunc(Math.random() * colord.length)];
  colorCode_3 = colord[Math.trunc(Math.random() * colord.length)];
  colorCode_4 = colord[Math.trunc(Math.random() * colord.length)];
  colorCode_5 = colord[Math.trunc(Math.random() * colord.length)];
  colorCode_6 = colord[Math.trunc(Math.random() * colord.length)];
  finalColor = colorCode_1 + colorCode_2 + colorCode_3 + colorCode_4 + colorCode_5 + colorCode_6;
  finalColorHex = '#' + finalColor;
  document.getElementById('h1element').innerHTML = finalColor;
  document.body.style.backgroundColor = finalColorHex;
  setTimeout(function() {
    clearInterval(interval);
    addTimeout();
  }, 2500);
}

function addTimeout() {
  if (timex <= 1000) {
    timex = timex + 100;
    both();
  } else if (timex <= 2500) {
    timex = timex + 250;
    both();
  } else if (timex <= 5000) {
    both();
  }
}

function both() {
  addTimeout();
  doThat();
}
doThat();
<center><h1 id="h1element">

</h1></center>

3 个答案:

答案 0 :(得分:1)

我会做这样的事情。

const colord = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];

let refreshRateIncrease = 50;
let initialRefreshRate  = 0;
const maxMili             = 2000; //2 seconds

function randomNumber(max){
  return Math.floor(Math.random() * max);
}

function fastToSlow(refreshRate){
  setTimeout(function(){

    let color = "";
    for(let i = 0; i < 6; i++){
      color += colord[randomNumber(colord.length)];
    }

    document.body.innerHTML = color;
    document.body.style.backgroundColor = '#' + color;

    //make it slower...
    refreshRate += refreshRateIncrease;
    //increase the refreshRateIncrease so it becomes slower much more quicklier
    refreshRateIncrease += 0.2 * refreshRateIncrease;
    //if the time passes a certain point, quit.
    if(refreshRate >= maxMili){
      return;
    }
    
    //call fast to slow again with the new refreshRate
    fastToSlow(refreshRate);
  }, refreshRate);
}

fastToSlow(initialRefreshRate);

答案 1 :(得分:0)

// Function that gives you a random number
function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

// Generates an hexadecimal color like "#45FF04"
function generateColor() {
  const arr = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
  ];

  let color = '#';

  for (let i = 0; i < 6; i += 1) {
    color = `${color}${arr[getRandomInt(arr.length - 1)]}`;
  }

  return color;
}

// Change i to go slower
const i = 10;

let timeToWaitForAChange = 50;

// Change increasingSpeed to makes more time to display all colors
let increasingSpeed = 100;
let nbColorChange = 0;

// How many colors you want to display ?
const maxNbColorChange = 50;


// Ex: If you want all 50 colors to be played very fast, use :
// i = 1
// inscreasingSpeed = 1

// Perform a color change and trigger the next one using setTimeout
function changeTheColor() {
  // Get the new color to apply
  const color = generateColor();

  // Apply the color
  document.getElementById('h1element').innerHTML = color;
  document.body.style.backgroundColor = color;

  // Decide the next delay to change the color
  timeToWaitForAChange += increasingSpeed;

  nbColorChange += 1;

  increasingSpeed = (nbColorChange * i);

  if (nbColorChange >= maxNbColorChange) {
    // It was the last stop
    return;
  }

  setTimeout(() => changeTheColor(), timeToWaitForAChange);
}

changeTheColor();
<center>
  <h1 id="h1element">

  </h1>
</center>

答案 2 :(得分:0)

您试图做的事情叫做“缓动功能”,您可以了解它们here

您真正需要的是“缓出”功能,我为您选择了“缓出通函”功能,您可以尝试其他任何具有类似特征的功能。在下面的代码中,您可以配置更新数量和更新持续时间以达到预期的效果,我在5秒钟内选择了100个更新。

const { floor, random, sqrt } = Math;
const { now } = Date;

const randomColor = () => `#${Array.from(Array(3), () => floor(random() * 255).toString(16).padStart(2, '0')).join('')}`;

const element = document.getElementById('h1element');
const bodyStyle = document.body.style;

const duration = 5000;

const start = now();

const totalUpdates = 100;

let elapsed = 0;
let updates = 0;

const easeOutCirc = (t, b, c, d) => {

    t /= d;
    t--;

    return c * sqrt(1 - t*t) + b;
}

const changeColor = () => {

    const color = randomColor();
    
    elapsed = now() - start;
    
    const newUpdates = floor(easeOutCirc(elapsed, 0, totalUpdates, duration));
    
    if (newUpdates > updates) {
        updates = newUpdates;
        
        bodyStyle.background = color;
        element.innerHTML = color;
    }
    
    if (updates < totalUpdates) {
        requestAnimationFrame(changeColor);
    }
};

changeColor();
<center><h1 id="h1element"></h1></center>