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.

1 Answers1

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);
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55