0

I need to loop and change the "hititle" word within 2 seconds

I tried sleep() and await wait() but it doesn't work.

Script:

function looptext() {
  while(true) {
    document.getElementById("hititle").value = '1';
    wait(2000)
    document.getElementById("hititle").value = '2';
    wait(2000)
    document.getElementById("hititle").value = '3';
    wait(2000)
    document.getElementById("hititle").value = '4';
    wait(2000)
    document.getElementById("hititle").value = '5';
  }
}
ducc
  • 82
  • 8

2 Answers2

1

You can do somthing like this without await:

const elem = document.getElementById("hititle");
elem.innerText = 1;
setInterval(() => {
  if (Number(elem.innerText) == 5) {
    elem.innerText = 1;
  } else {
    elem.innerText = Number(elem.innerText) + 1;
  }
}, 2000)
<div id="hititle"></div>
Harsh Saini
  • 598
  • 4
  • 13
  • You should avoid checking the `innerText` property, first it may cause a synchronous reflow, and it may not return what you expect based on how the element is rendered. Better use `textContent` instead. But here it would even be better to save the value as a number in a variable: `let i = 0; setInterval(() => { i = (i + 1) % 5; elem.textContent = i + 1; }, 2000); elem.textContent = i + 1;` – Kaiido Nov 25 '21 at 04:39
0
<input id="hititle">

And your JS should be...

async function looptext() {
  while(true) {
    document.getElementById("hititle").value = '1';
    await sleep(2000)
    document.getElementById("hititle").value = '2';
    await sleep(2000)
    document.getElementById("hititle").value = '3';
    await sleep(2000)
    document.getElementById("hititle").value = '4';
    await sleep(2000)
    document.getElementById("hititle").value = '5';
  }
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

looptext();

See it in action

vee
  • 4,506
  • 5
  • 44
  • 81