"document.write can be a form of eval"?

2.1k Views Asked by At

I'm new to JavaScript and am trying to write code that does the following: Write some code that writes "1" to the console, then 1 second later writes "2" to the console, then 2 seconds after that writes "3" to the console, ..., until it gets to "10".
I've tried both the setTimeout and the setInterval + combined with setTimeout and I seem to be getting the same persistent error: document.write can be a form of eval. What does this mean and is there any different way I can code this to achieve the result I'm looking for?

var count = 1;
  setTimeout(function () {
    document.write(count);
    count += 1;
  }, 1000;
  print {
    document.write(10), 10000
  });

I understand sometimes this occurs when I have an undefined parameter, but in this case, I believe count is defined?

3

There are 3 best solutions below

0
James McDowell On BEST ANSWER

Based off your problem, I'd go at it a bit differently. This will work, but I'm not completely sure it's what you're looking for

var run = function(start, stop){//In your case, start is 1 and stop is 10
  var currentPos = start;
  var loop = function(){
    setTimeout(function(){
      document.write(currentPos + "<br/>");
      if(++currentPos <= stop)
        loop();
    }, (currentPos - 1) * 1000);
  }
  loop();
}
run(1, 10);

0
Amr Morsy On
var limit = 10,
  i = 0;

function step() {
  setTimeout(function() {
    if (i < 10) console.log(++i);
    step();
  }, 1000);

}

step();

http://codepen.io/anon/pen/YXxwxB

0
Wade Bear On

I realize this is an old question, but I just want to point out that only Amr Morsy used the correct output, but didn't explain why. The original question states: "Write some code that writes "1" to the console, then 1 second later writes "2" to the console, then 2 seconds after that writes "3" to the console, ..., until it gets to "10"." The Console is part of the web development tools built into some (all?) browsers that allows you to see behind the scenes stuff. For Firefox, hold Shift and Ctrl while tapping the k and it will come up. You write to the console by using console.log().