0

What I want is when the first (.goccia) element reach the bottom of the screen the set interval function stop.

function spostaGocce(){
var goccia = document.querySelectorAll('.goccia');
for(i = 0; i < goccia.length; i++){ 
goccia[i].style.top = parseInt(goccia[i].style.top ||0) + Math.round(Math.random() * 2) + 1 
+ 'px';
}
}
function muoviti(){
setInterval(spostaGocce, 30);
}
document.querySelector('button').addEventListener('click', muoviti);

I tried to create a variable like this:

gocciaTop = goccia.getBoundingClientRect().top

and then do an 'if' like this:

if(gocciaTop == window.innerHeight){
document.write('done')
}

But he gave me an error that say that 'getBoundingClientRect() is not a function'.

Davide
  • 21
  • 3

2 Answers2

1

you can use clearInterval() function. Forexample in you case. you will create a variable

var intervalId;

and then in you muoviti() function you will assign you setInterval reference to the above variable.

function muoviti(){
  intervalId = setInterval(spostaGocce, 30);
}

And then once you are done, like in the following if condition do this:

if(gocciaTop == window.innerHeight){
  clearInterval(intervalId);
  document.write('done')
}
noman tufail
  • 341
  • 2
  • 8
  • `clearInterval()` is why it exists. Up voting this. Don't know about the `window.innerHeight()` as applies to OP but `clearInterval()` correct way to cancel an interval timer in javascript. Provided you assigned the `setInterval()` a result variable in *scope*. – GetSet Feb 26 '20 at 09:09
0

if condition and the variable gocciaTop should be inside the for loop.

function spostaGocce(){
    var goccia = document.querySelectorAll('.goccia');
    for(i = 0; i < goccia.length; i++){ 
        goccia[i].style.top = parseInt(goccia[i].style.top ||0) + Math.round(Math.random() * 2) + 1 
        + 'px';
        var gocciaTop = goccia[i].getBoundingClientRect().top;

        if(gocciaTop == window.innerHeight){
         clearInterval(Int);
        }
    }
}
var Int;

function muoviti(){
    Int = setInterval(spostaGocce, 30);
}

document.querySelector('button').addEventListener('click', muoviti);
Wilson
  • 329
  • 2
  • 11