0

I am new at javascript. I want to create a for loop that iterate after 1 second.

for(sec=60;sec>0; sec--){
    document.write(sec);    
}

When i use above code, for loop print everything immediately.I want that for loop executes every 1 second. I know it can be done by using setInterval(); function but i don't know how to do it exactly. Please suggest me best solution how to do.

4
  • Then why won't you use setInterval? Sep 30, 2017 at 4:30
  • i don't know how to use it. Please tell me Sep 30, 2017 at 4:30
  • setTimeout(function(){}, 1000);
    – Justin
    Sep 30, 2017 at 4:31
  • Please add in my code, how to do it. Please sir Sep 30, 2017 at 4:34

1 Answer 1

0

You can use setInterval to run at every 1 second, and then use clearInterval to prevent any further executions once the count is 60.

var count = 1;

var interval = setInterval(function() {
  
  console.log("Count: " + count);
  
  if(count == 60)
  {
    clearInterval(interval);
  }
  else 
  {
    count++;
  }
},1000);

2
  • can't it be done in for loop? Sep 30, 2017 at 4:35
  • Why do you need a for loop now? Sep 30, 2017 at 4:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.