-1

I am trying to write code to scroll down a div on a website. The div has countent which is automatically loaded when you scroll to the bottom. I am accomplishing this by adding an element with a link to itself, clicking it, removing it, and then re-adding (to the new bottom). My code looks like this:

function showWholeDiv() {
    clearTimeout();
    console.log("Running:");
    let contents;
    let myDiv = document.getElementsByClassName("{classname}")[0];
    contents = myDiv.children;
    let elem = document.createElement("a");
    elem.id = "scroll-here";
    elem.href = "#scroll-here";
    myDiv.appendChild(elem);
    scrollDiv(myDiv, elem, 10);
};

function scrollDiv(div, scrollElem, scrolls) {
    clearTimeout();
    if (scrolls > 0) {
        console.log("scrolling...");
        div.appendChild(scrollElem);
        document.getElementById("scroll-here").click();
        scrollElem.remove();
        setTimeout(scrollDiv(div, scrollElem, scrolls - 1), 100);
    } else {
        console.log(div);
    }
};

It works for one scroll but then I get this weird message and it outputs "scrolling..." over and over all at once without the delay:

scrolling...
680a7736f556.js:44 [Violation] 'setTimeout' handler took 179ms
contentScript.js:34 scrolling...
680a7736f556.js:44 [Violation] 'setTimeout' handler took 143ms
contentScript.js:34 scrolling...
680a7736f556.js:44 [Violation] 'setTimeout' handler took 162ms
contentScript.js:34 scrolling...
680a7736f556.js:44 [Violation] 'setTimeout' handler took 154ms
contentScript.js:40 <div class=​"PZuss">​…​</div>​

I added the clearTimeouts to see if that was the problem but it didn't help. What is going on here? Is there something about setTimeout I am misunderstanding?

1 Answers1

0

The scrollDiv function is being evaluated immediately.

One way to solve this would be to wrap it in a closure

setTimeout(function() {scrollDiv(div, scrollElem, scrolls - 1}), 100);

Martin Beeby
  • 4,523
  • 1
  • 26
  • 20