Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
SetTimeout not working inside async eventListener

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";
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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 onload:

if (window.location.pathname == "/movies") {
  window.onload = populateForm;
  console.log(sessionStorage);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!