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>
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 )
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With