Olly F
Olly F

Reputation: 255

JS loop that runs forwards, reaches the end then runs backwards and forwards indefinitely

I am using a bit of JS that changes the value of an HTML attribute, it uses setInterval and goes from 0-150, reaches 150 and starts again back to 0.

I am trying to work out if its possible to reach the end then run backwards, like:

-150 ==> 0 ==> 150 ==> 0 ==> -150 ==> 0 etc

This is the code I am using at the moment:

var liquifyVal = -150
window.setInterval(function() {
  liquifyVal = (liquifyVal + 1) % 150;
  document.getElementById('liquid').setAttribute('scale', liquifyVal);
}, 25);
h1 {
  filter: url("#liquify");
  font-size: 100px;
}
<h1>
  Hello
</h1>
<svg id="svgeffects">
	  <defs>
		<filter class="safari_only" id="liquify">
			<feTurbulence baseFrequency="0.015" numOctaves="2" result="warp" type="fractalNoise"></feTurbulence>
			<feDisplacementMap id="liquid" in="SourceGraphic" in2="warp" scale="150" xChannelSelector="R" yChannelSelector="B"></feDisplacementMap>
		</filter>
	  </defs>
	</svg>

Fiddle here https://jsfiddle.net/8efk2a1q/ (think this only works in Chrome for now)

Design explanation-wise its so there isn't a jarring end to the animation, instead there is a seamless back and forwards.

Any help would be great!

Thanks.

Upvotes: 0

Views: 74

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

You could declare an increment variable outside of the loop, and assign it 1 or -1 when the peak/trough is reached. It would also be nicer to only select the element in question once, rather than over and over again each time the interval runs:

const liquid = document.getElementById('liquid');
let liquifyVal = -150;
let increment = 1;
setInterval(() => {
  liquifyVal += increment;
  if (liquifyVal === 150) increment = -1;
  else if (liquifyVal === -150) increment = 1;
  liquid.setAttribute('scale', liquifyVal);
}, 25);
h1 {
  filter: url("#liquify");
  font-size: 100px;
}
<h1>
  Hello
</h1>
<svg id="svgeffects">
  <defs>
    <filter class="safari_only" id="liquify">
      <feTurbulence baseFrequency="0.015" numOctaves="2" result="warp" type="fractalNoise"></feTurbulence>
      <feDisplacementMap id="liquid" in="SourceGraphic" in2="warp" scale="150" xChannelSelector="R" yChannelSelector="B"></feDisplacementMap>
    </filter>
  </defs>
</svg>

Upvotes: 3

Related Questions