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';
  }
}
2
  • 1
    What do you mean it doesn't work? What actual you got? Commented Nov 25, 2021 at 3:22
  • Does this answer your question? Commented Nov 25, 2021 at 3:23

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

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;
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.