1

I try to animate the Clip-Path Property with JavaScript.

Means: It "grows" with help of SetTimeout.

I tried this, but it doesn't work. http://jsfiddle.net/071dm2h3/8/

var el = document.getElementById("image")

function grow(i) {
    el.style.clipPath = "circle("+ i +"px at 190px 160px)";
}

var i;
for(i = 0; i < 100; i++) {
  setTimeout(grow(i), 400);
}

What am I missing here? Shouldn't the setTimeout change the value of I in every loop, so that I can see the result immediately?

3 Answers3

0

To get this to work, I rewrote your setTimeout to be around your loop to make the image grow.

setTimeout( function(){ 
 for(i = 0; i < 100; i++) {
  grow(i)
 }
},400);

Here is the jsfiddle

EliTownsend
  • 181
  • 11
0

No, setTimeout fires once, and only once. Additionally, the way you are using setTimeout will lead to unintended results. You are basically saying:

I want to call grow(i) 400 milliseconds from now 100 times.

That means that 400 milliseconds from now, grow(i) will be called 100 times simultaneously. You don't want that, you want to call `grow(i) 100 times, waiting 400 milliseconds between each iteration.

Instead, you should either use setInterval which will wait a duration between each call or have each setTimeout schedule the next timeout after a duration.

Consider:

This will wait 2 seconds and then print 1,2,3,4 all at the same time.

for (let i = 0; i < 5; i++) {
  setTimeout(() => console.log(i), 2000);
}

This will print each iteration after a duration:

function iteration(i) {
  console.log(i);
  if (i > 3) return;
  setTimeout(() => iteration(i + 1), 500);
}

iteration(0);
zero298
  • 25,467
  • 10
  • 75
  • 100
0

change you javascript to this

var el = document.getElementById("image")

function grow(i) {
console.log(i)
    el.style.clipPath = "circle("+ i +"px at 190px 160px)";
}

var i;
for(i = 0; i < 100; i++) {
  setTimeout( ((i) => () =>  grow(i))(i), i*10);
}

and kindly read this once setTimeout in for-loop does not print consecutive values

ashish singh
  • 6,526
  • 2
  • 15
  • 35