Home > OS >  How to do timeout with loop function in js
How to do timeout with loop function in js

Time:11-25

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

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

<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

  • Related