I am new to JS.
I need an array variable which is used to display the values periodically every 1s using setInterval() inside a function.
The array variable for ex intV[] (setInterval variable) should display the values when used in console.log(intV[]); and the values should be stored in intV[].
I tried the below code,
But it didn't work.
function date() {
var currentDate = Date.now();
var val = String(currentDate).substr(8, 2);
return val;
}
var intV = [];
function mockData(v) {
var v = document.getElementById('sample');
//setInterval function
intV[v] = setInterval(date, 1000);
console.log(intV[v]);
}
When I did console.log(intV[v]);. It doesn't display the values every 1s. Instead, it gives a static value Which is not updated every 1s.
How could i store the values, which is updated every 1s in the intV[].?
Could someone please help? Many thanks.
The setInterval method expects a function as a parameter which is run at each specified interval. All of the logic, including console.log needs to be inside of the function that you pass to setInterval. I believe the sample provided below provides what you are looking for, but you need to understand that the intV array will be populated AS the intervals occur, NOT before.
var intV = [];
function date() {
var currentDate = Date.now();
var val = String(currentDate).substr(8, 2);
intV.push(val);
console.log(intV[intV.length - 1])
}
//setInterval function
setInterval(date, 1000);