Byakugan Byakugan - 1 month ago 5
Javascript Question

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>

Answer

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 )

Comments