0

I wrote some lines below:

function testScroll() {
    if (window.pageYOffset > 400) {
        for (var x=0; x<=2; x++){
            newCircle(circle[x],circleId[x],startColorId[x],endColorId[x]);
        }; 
    };
};

window.onscroll = testScroll;

function works showing newCircles but it does as many times as user scroll down the page, the ideal will when the function stop if there are appering three circles on page,

I tried to change if condition to equal but it doesnt help, if you have any ideas please help

ArneHugo
  • 6,051
  • 1
  • 26
  • 47
artjuzwik
  • 31
  • 2
  • 1
    `onscroll` fires several times per second, you need a [debouncer](https://stackoverflow.com/a/4298672/1169519). Or when re-reading the question, rather set `window.onscroll` to `null` at the end of the handler function ... – Teemu Jun 14 '17 at 11:22
  • nulling window.onscroll worked perfectly thx, is it bad practice? – artjuzwik Jun 14 '17 at 11:34
  • Not worse than setting it to refer a function = ). It just removes the event listener. – Teemu Jun 14 '17 at 11:35
  • Removing the listener (like @Teemu suggested above) is the best solution if you no longer need to respond to the event (in this case scroll event). It uses less resources and often makes code easier to understand as well. – ArneHugo Jun 14 '17 at 11:38

2 Answers2

0

Your current function creates 3 circles each time you scroll.

If you want to have MAX 3 circles; perform the following change :

var _countCirlces =0; // initial circles count
function testScroll(ev){

    if(window.pageYOffset>400) {
        // create 1 circle for each scroll + increment _countCircles
        newCircle(circle[x],circleId[x],startColorId[x],endColorId[x]);
        _countCircles++;

    };return;

};

window.onscroll=testScroll;
aorfevre
  • 5,034
  • 3
  • 21
  • 51
0
var _circleCount = 0;

function testScroll(ev) {

    if(window.pageYOffset>400 && _circleCount < 2) {
        for (var x=0; x<=2; x++) {
            newCircle(circle[x], circleId[x], startColorId[x], endColorId[x]);
            _circleCount++;
        }; 
    };
    return;
};

window.onscroll = testScroll;
Phylleo
  • 1
  • 1