-2

I am trying to show the countdown inside the span tags(but it's not showing) and how do I stop it from printing number again and again (if it works).

<span></span>

<script>
    const countDown = (counter) => {
            const displayer = document.querySelector('span');
            for (counter = 10; counter >= 0; counter--) {
                return displayer.counter
            }
        }
</script>
Perfectó
  • 91
  • 6
  • 1
    Instead of inventing your own properties, maybe reading how the [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) works helps to create a DOM manipulator. – Teemu Jun 23 '21 at 10:02
  • Your code makes no sense. DOM elements does not have `.counter`; you do nothing with `countDown`, you never call it. Your loop is stopped automatically when `counter` reaches 0. Maybe do `displayer.innerText = counter`? – Justinas Jun 23 '21 at 10:04
  • Does this answer your question? [Change span text?](https://stackoverflow.com/questions/8177215/change-span-text) – Justinas Jun 23 '21 at 10:05
  • An unconditional return statement in a loop doesn't make sense. It will always leave the loop after the first iteration. –  Jun 23 '21 at 10:06
  • Oh, and all you will see is `10`, since loop is synchronous and user will see only last iteration result. And last iteration is 10, because loop returns on first iteration – Justinas Jun 23 '21 at 10:06

2 Answers2

1

Looking for something like this?

  • displayer.innerText = counter; to update the text of the element.
  • Make a delay inside the loop, otherwise you will not see the change 10,9,8...0 because the loops runs in microseconds to it's end

const delay = (time) => new Promise((r) => setTimeout(r, time));

const countDown = async (counter) => {
  const displayer = document.querySelector('span');
  for (counter = 10; counter >= 0; counter--) {
    displayer.innerText = counter;
    await delay(1000);
  }
}


countDown(10);
<span></span>
stacj
  • 1,103
  • 1
  • 7
  • 20
-1

This will work so fast and you'll never see 10, 9, 8, ...

1-Problem can be about querySelector() to select correct element

2-You must use setInterval() or setTimeout() methods for these kind applications..

3-you are trying to show counter object inside displayer in return statement, you may use displayer.innerHTML=counter to write counter variable inside span element