silicoin silicoin - 23 days ago 7
CSS Question

Javascript setInterval() runs the function only once

I have this code, where I'm trying to animate one of the divs. The div should move down, then after getting 20% lower should start moving up, then again down and so on.

The problem is, as it seems, that the code runs only once. Which means the div moves down by 2% only once and then stays at that position.

Javascript

var head = document.getElementById('char_furuta_head');
function anime() {
var direction = 1; /* 1 = down, -1 = up */
setInterval(frame, 1000);
function frame() {
str = head.style.top;
str = substring(0,str.length);
var lel = parseInt(str);
console.log(lel);

if (direction == 1) {
lel += 2;
head.style.top = lel + '%';
if(lel == 20) { direction = -1; };
} else {
lel -= 2;
head.style.top = lel + '%';
if(lel == 0) { direction = 1; };
}
}
}

Answer

You've misdiagnosed the problem.

The interval is running fine.

You need to debug it properly. Add console.log statements to see when functions are called and what the values of your variables are:

    var lel = head.style.top;
    lel += 2;
    head.style.top = lel + '%';

The first time you call that:

  1. lel is an empty string
  2. lel is 2
  3. head.style.top is 2%

The second time:

  1. lel is 2%
  2. lel is 2%2
  3. head.style.top is 2% because 2%2 is invalid

The third time repeats the second time.

Use parseInt to extract the number from the length.