Reputation: 11
i want to change name by using increment function, that will change name every 300 msec
class NumberModel {
constructor () {
this.color = 'red';
}
increment () {
const colors = ['orange', 'red', 'green', 'blue'];
setInterval(()=>{this.color = colors[Math.floor(Math.random()*colors.length)];
console.log(this.color)},300);
but when i create object and applied function increment and run this code nothing happens
Upvotes: 1
Views: 35
Reputation: 116
I understand that the goal is for every 0.3 seconds to select a random color from the array and prints it in the console.
class NumberModel {
constructor() {
this.color = 'red';
}
increment() {
const colors = ['orange', 'red', 'green', 'blue'];
setInterval(() => {
this.color = colors[Math.floor(Math.random() * colors.length)];
console.log(this.color)
}, 300);
}
}
const numberModelOne = new NumberModel
numberModelOne.increment() //prints every 0.3 eternally random color from the array
In my case, it's working well.
But you missed closing some curly brackets. Add } x 2 at the end.
Upvotes: 0
Reputation: 503
Looks like you misspell somewhere. check here https://stackblitz.com/edit/js-mgq54z?file=index.js
Upvotes: 1
Reputation: 11283
I don't see any issues with the code.
Take a look at the following snippet.
class NumberModel {
constructor() {
this.color = 'red';
}
increment() {
const colors = ['orange', 'red', 'green', 'blue'];
setInterval(() => {
const randomIndex = Math.floor(Math.random() * colors.length)
this.color = colors[randomIndex];
console.log(this.color)
}, 300);
}
}
const numberModel = new NumberModel()
numberModel.increment();
Upvotes: 1
Reputation: 846
It's working at my end:
class NumberModel {
constructor () {
this.color = 'red';
}
increment () {
const colors = ['orange', 'red', 'green', 'blue'];
setInterval(()=>{this.color = colors[Math.floor(Math.random()*colors.length)];
console.log(this.color)},300);
}
}
then use it like:
var nm = new NumberModel();
nm.increment();
Upvotes: 1