Skip to main content

Command Palette

Search for a command to run...

JavaScript: Print 10 numbers with a delay of 3 seconds

Updated
1 min read
JavaScript: Print 10 numbers with a delay of 3 seconds
H

Full stack developer (ReactJS, NodeJS, JavaScript, PHP, SQL)

// Method 1
for (let i =1; i<=5; i++) {
      setTimeout(function() {
      console.log(i)
      }, i * 3000);
  }

// Method 2
for (var i =1; i<=5; i++) {
    (function foo(i) {
      setTimeout(function() {
      console.log(i)
      }, i * 3000);
    })(i) // IIFE
}

// Method 3
var i=1;
const interval = setInterval(() => {
    if(i==5) {
        clearInterval(interval);
    }
    console.log(i++);
 }, 3000);

More from this blog

E

Everyday Dev Patterns

26 posts

A collection of real-world JavaScript snippets, patterns, and gotchas from my day-to-day work.