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

123
Views
problem with setting loading animation class during sync JS work

I'm working on visual version of my sorting algorithm and I would like to show to the user a loading animaton during the sorting itself by JS. But the problem is that JS behaves weird then. It executes the first line and the last line (2 x toggle) and the launches the execution of the alogrithm. But if I add setTimeout (2nd function) it works as it should. Could anyone, please, explain to me how it works ? I've already tried to do a lot of reasearch but to no avail... It's counter-intuitive - because in first example it behaves like JS was asynchronous (1 -> first line animation added and 2 -> the last line animation removed, 3 -> the sorting work) and in the second example after adding setTimeout as synchronous (1 -> first line animation added, 2 -> sorting work, 3 -> animation removed)

function sortArray() {
  mainWrapper.classList.toggle("spinner-hidden");
  arrayCopy = [...arrayToSort];
  const sortedArray = bearSort(arrayCopy);
  outputArray.textContent = sortedArray;
  mainWrapper.classList.toggle("spinner-hidden");
}

function sortArray() {
  mainWrapper.classList.toggle("spinner-hidden");
  arrayCopy = [...arrayToSort];
  setTimeout(() => {
    const sortedArray = bearSort(arrayCopy);
    outputArray.textContent = sortedArray;
    mainWrapper.classList.toggle("spinner-hidden");
  }, 0);
}
about 4 years ago · Juan Pablo Isaza
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!