Home > Software engineering >  SetTimeout not working inside async eventListener
SetTimeout not working inside async eventListener

Time:11-13

In the following function I am adding an eventlistener to every li, up until the setTimeout everything work as expected.
Neither the console.log nor the populateForm() execute. I have tried a bunch of different methods but nothing seams to work.

async function addClickListener() {
  const items = document.querySelectorAll(".li");
  items.forEach((item) => {
    item.addEventListener("click", async (evt) => {
      evt.preventDefault();
      sessionStorage.clear();
      const movieData = await createMovieObject(evt.currentTarget);
      sessionStorage.setItem("movieData", JSON.stringify(movieData));
      clearMovieList();
      removeHidden();
      switchToSearch();
      setTimeout(function () {
        console.log("hello");
        populateForm();
      }, 5000);
    });
  });
}

I tried calling await delay(5000); instead of the setTimeout like above but this doesn't work either

 const delay = (ms) =>
  new Promise(() => {
    setTimeout(() => {
      console.log("hello");
      populateForm();
    }, ms);
  });

Here is the populateForm() function

function populateForm() {
  const check = document.querySelector("#added_movies");
  console.log(sessionStorage);
  console.log(check);
}

Here is the switchToSearch() function, it seams that this is causing the issue as I am changing links and the console is maybe reset (just an assumption)?!

function switchToSearch() {
  window.location.href = "./movies";
}

CodePudding user response:

With window.location.href = "./movies"; a new document is loaded and all Timeouts, EventListeners, … are released. So your registered timeout won’t be executed.

CodePudding user response:

I have marked @t.niese ansewer as accepted since this is the underlying problem I am facing.
One thing that I would like to note though is that although code in the setTimeout() did not work, code that followed, for example an console.log('I am on the new page') would work right after the switchToSearch();.

Anyway, I have continued now and made it work via an onl oad:

if (window.location.pathname == "/movies") {
  window.onload = populateForm;
  console.log(sessionStorage);
}
  • Related