Jump to content

How to make this simple javascript code work?

Featured Replies

<html>
<head>
</head>
<body>


<script>

 

i=0;
for (i=0; i<100; i++)
 { document.write(".");  
  setTmeout( null,100);       
}
</script>
</body>
</html>

I want to print 100 dots, after one dot, rest 0.1 second.

I do NOT use to use the statement "setTimeout(function, s)";

I want to set the function to null, but it does NOT work, how to make it work as the function is null.

Was a typo, setTimeout is missing an 'i'.

 

I think you do need to have it call a function though.

Edited by Endy0816

setTimeout is async, i.e. it's non-blocking and will never work like this. The for loop would race ahead and make 100 setTimeouts all at once, then they'd all fire at more or less the same time, not 100 ms after each other.

Also, Endy0816 is right that the null cannot be used. You do need to call a function, or have a string that evaluates to code, or use a lambda (arrow function).

This works:

<html>
<head></head>
<body>
<p>Test:</p>
<script>
let i = 100;
setTimeout(ShowDot, 100);

function ShowDot() {
  document.write(".");

  if (i-- > 1) {
    setTimeout(ShowDot, 100);
  }
}
</script>
</body>
</html>

If you want the first dot to show immediately, just replace the first:

setTimeout(ShowDot, 100);

With:

ShowDot();

 

See: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout

Edited by pzkpfw

Please sign in to comment

You will be able to leave a comment after signing in

Sign In Now

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.