Ask coding questions

← Back to all posts
how to wait in HTML
sweetmango88 (16)

Hello! I don't know how to "wait" some code in HTML. If you don't understand here is an example;

<!doctypehtml><html> <script> console.log("hello") //how do I wait for 1 second and then move on with the code. console.log("there") //and so on </script> </html>
Answered by ch1ck3n (2052) [earned 5 cycles]
View Answer
Comments
hotnewtop
ch1ck3n (2052)
  1. it's called javascript
<!doctypehtml>
<html>
   <script> setTimeout(function(){console.log("hello")setTimeout(function(){console.log("there")}, 2000)}, 1000)</script> 
</html>

ez

ch1ck3n (2052)

@sweetmango88 well whats inside the <script> tags are called javascript look it up

[deleted]

@ch1ck3n yes don’t forget the closing tag

<script></script>
sweetmango88 (16)

The <script> thing is actually HTML it refers to javascript but it is html itself....................... I think.....

[deleted]

@ch1ck3n you forgot . In .setTimeout

ch1ck3n (2052)

@sweetmango88 the TAG is html but what's inside it is javascript

ch1ck3n (2052)

@TestOP there is no . in setTimeout

sweetmango88 (16)

@ch1ck3n yes ;-;.......................................... OH I get it..

sweetmango88 (16)

@ch1ck3n but what if I want to console.log another thing and wait again?

ch1ck3n (2052)

@sweetmango88 my code does exactly that

[deleted]

@ch1ck3n ooops

notGilbert (121)

@ch1ck3n you might want to use promises, async, and await to prevent callback hell

instead of:

setTimeout(() => {
  console.log('1');

  setTimeout(() => {
    console.log('2');

    setTimeout(() => {
      console.log('3');

      setTimeout(() => {
        console.log('4');
      }, 1000)
    }, 1000)
  }, 1000)
}, 1000)

do this:

// returns a Promise that resolves after ms time
function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}

// async functions will allow you to use await, which waits for a Promise to be resolved
async function run() {
  await sleep(1000);
  console.log('1');
  await sleep(1000);
  console.log('2');
  await sleep(1000);
  console.log('3');
  await sleep(1000);
  console.log('4');
}

run(); // call the function