Error with asynchronism in Javascript

Asked

Viewed 34 times

-2

Guys, have a list (on a web page) that when I scroll it carries new elements, Suppose it is the list [john, paul, peter], by giving scroll as said earlier it will hypothetically carry the elements [john, paul, peter, Fernando, maria]. I’m creating a code that will load all the elements to play them into a list. The dynamic is: when scrolling the window, the page requests the new elements from the list to the server. The problem is: I believe that the Current variable is receiving the value before the elements are loaded into the DOM, so the current one is always the same as the previous one. This loop would scroll until all the elements in the list have been loaded on screen.

I thought to set a setTimeOut after the scroll is done, but this would make the script too slow.

function dissect(node){
    //essa função só serve para navegar em um elemento da DOM
    node = node.firstChild;
    node = node.childNodes;
    node = node[0];
    node = node.firstChild;
    node = node.lastChild;
    return(node.getAttribute('href'));
}

function loadWindow(){
    //recovering last child
    var seguidores = document.querySelector('div.PZuss');
    var last = dissect(seguidores.lastChild);
    var current = undefined;

    //recovering window
    var window = document.querySelector('div.isgrP');
    console.log(window);

    while(current != last){
        last = dissect(seguidores.lastChild);
        window.scroll(0, 1000);
        current = dissect(seguidores.lastChild);

    }
}

loadWindow();

2 answers

0

If you believe that the problem caused is because an element has not loaded yet, you can check if the element exists, with the following JS

if (document.getElementById('id_elemento')){
 //Agora você pode setar valor na variável current
    console.log('existe');
} 
  • There is no way, this list contains only classes. I made an edit on the question and added its code.

  • Document.querySelector wouldn’t work? Or grab the path through the console?

0

How’s your search method? If your problem is really him doing the search and not waiting, you can use async/await or use a then in his presidency

Browser other questions tagged

You are not signed in. Login or sign up in order to post.