0

I've the following code that should have to works for a slider:

let timeOut, timeOut2;
over = 1;
let back = 0;
setInterval(change2, 8000);

 async function change2() {
  innerFront = slides[over];
  innerBack = slides[back];
  await setTimeout(change, 8000);

  innerFront.querySelectorAll('figure')[0].classList.remove('isActive');
  innerFront.classList.remove('slideshow__inner--front');
  innerBack.querySelectorAll('figure')[0].classList.remove('isActive');
  innerBack.classList.remove('slideshow__inner--back');
  over -= 1;
  if (over < 0) over = slides.lenght;
  back = over - 1;
  if (back < 0) back = slides.lenght;
  slides[over].classList.add('slideshow__inner--front');
  slides[back].classList.add('slideshow__inner--back');
}

function change() {
  return new Promise(function(resolve, reject) {
    innerFront.querySelectorAll('figure')[0].classList.add('isActive');
    timeOut2 = setTimeout(()=> {
      innerBack.querySelectorAll('figure')[0].classList.add('isActive');
    }, 1000);
    resolve();
  });
}

My problem consists in the fact that the 'change' function seems not to be performed despite the Await for Promise. In fact, the subsequent instructions are immediately performed, and obviously this generate errors. I still have doubts about the promises, which I am studying, and here I think there can be something conceptual. Does anyone have the patience to explain to me where I'm wrong?

BennyB
  • 35
  • 1
  • 7
  • 1. You `resolve` the promise in `change` without waiting for the `setTimeout` – Quentin May 12 '22 at 13:09
  • `setTimeout()` does not return a Promise instance. It returns a number that identifies the timer request. The returned value from the timer callback, Promise or not, is ignored. – Pointy May 12 '22 at 13:09
  • 2. In `change2` (a) `setTimeout` doesn't care if its callback returns a promise. (b) `setTimeout` returns a number and it isn't useful to `await` a number. – Quentin May 12 '22 at 13:10
  • 1
    `setTimeout` does not return a promise and is therefore not `await`able. See https://stackoverflow.com/a/39914235/14357 on how to wrap up setTimeout in a promise – spender May 12 '22 at 13:10
  • Ok, I've to improve my studying... anyway, how I can correct the routine? – BennyB May 12 '22 at 13:25

1 Answers1

0

There's a typo inside of change2() you wrote lenght instead of length twice.

ToluMals
  • 11
  • 2