0

I have this code that I can get to out numbers 0 - 9:

var countup = {
    i: 0,
    startCount: function () {
        for(i = 0; i < 10; i++){
            console.log(i);
        }
    }
}

countup.startCount();

now I need to be able to get it to output the numbers at 1 second intervals, I have tried this code below that is just giving me an undefined output:

var countup = {
    i: 0,
    startCount: function () {
        setInterval(function() {
            for(i = 0; i < 10; i++){
                console.log(i);
            }
        }, 1000)
    }
}
countup.startCount();

Does anyone have have any ideas how I can edit the code above to give the desired output of numbers 0 - 9 at one second intervals?

Thanks!

jo_va
  • 13,504
  • 3
  • 23
  • 47

2 Answers2

4

See the second and third snippets for better answers.

You can do it like this, using setInterval and clearInterval when the count reaches 10. Also, to access the variable i in your countup object, you can do it with this.i:

const countup = {
    i: 0,
    startCount: function() {
        const timer = setInterval(() => {
            console.log(this.i);
            if (++this.i === 10) {
                clearInterval(timer);
            }
         }, 1000);
    }
}

countup.startCount();

As mentionned by @Hit-or-miss, this should not be used in a static object. Here is a better way to do it using the prototype.

This allows you to have multiple counters that don't share their internal count.

function Countup() {
  this.i = 0;
}

Countup.prototype = {
    constructor: Countup, // Good practice

    startCount: function() {
        const timer = setInterval(() => {
            console.log(this.i);
            if (++this.i === 10) {
                clearInterval(timer);
            }
        }, 1000);
    }
};

const counter1 = new Countup();
const counter2 = new Countup();

counter1.startCount();
counter2.startCount();

Or, using JavaScript classes:

The arrow functions and classes are supported only in modern browsers.

class Countup {
    constructor() {
        this.i = 0;
    }

    startCount() {
        const timer = setInterval(() => {
            console.log(this.i);
            if (++this.i === 10) {
                clearInterval(timer);
            }
        }, 1000);
    }
};

const counter1 = new Countup();
const counter2 = new Countup();

counter1.startCount();
counter2.startCount();
Hit-or-miss
  • 508
  • 1
  • 6
  • 16
jo_va
  • 13,504
  • 3
  • 23
  • 47
3

use let for declaring i and use setTimeout since you have to call console.log counter only ten times not forever..

var countup = {
  startCount: function () {
    for(let i = 0; i < 10; i++){
       setTimeout(function() {
         console.log(i);
       }, i*1000)
     }
   }
}
countup.startCount();
Gaurav Saraswat
  • 1,353
  • 8
  • 11