Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a script for odd and even numbers from 1 to 1000 in Javascript?

I am studying a book of Javascript with solved examples but there is one example without solution. I would like to know how to do it ...

In javascript (in browser) I should do is write even numbers from 1-1000 and after it is finished write odd numbers from 1-1000 ... I am not sure how to add there very small "pause" between number writing and how to know if first cycle is over and start writing odd numbers?

Here is How I started:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
 <head>
   <title>Test</title>
 </head>
 <body>
<script type="text/javascript">
/* <![CDATA[ */
var i;
for (i = 0; i < 1000; i++)
if ((i % 2) == 0)
  document.writeln(i);

/* ]]> */
</script>
 </body>
</html>
like image 517
Byakugan Avatar asked Oct 26 '25 15:10

Byakugan


2 Answers

Give this a try:

 function partA() {
        for (var i = 0; i < 1000; i++){
            if ((i % 2) == 0) document.write(i + ' ');
        }
        window.setTimeout(partB,1000)
    }

    function partB() {
        for (var i = 0; i < 1000; i++){
            if ((i % 2) !== 0) document.write(i + ' ');
        }
    }

    partA();

SIDENOTE:

Use document.write for testing only. If you execute it, on a loaded HTML document, all HTML elements will be overwritten. ( As you can see in my example )

like image 83
baao Avatar answered Oct 29 '25 05:10

baao


I was not able to make a pause occur between the iterations of counting. The below code, in place of your script, will give you 0-1000 evens, then odds, 1 per line.

There is some discussion of waiting in javascript already on the site: What's the equivalent of Java's Thread.sleep() in JavaScript?

<script>
for(var mod = 0; mod<2; mod++){
  for (var i = 0; i < 1000; i++)
    if ((i % 2) == mod)
      document.writeln(i+"<br>");
}
</script>
like image 35
Greg Syme Avatar answered Oct 29 '25 05:10

Greg Syme



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!