I'm a beginner and it'll show :( but could anyone assist me into the right direction? I have an object literal with arrays nested inside. I need to grab the first row of arrays then push the values of that row into the three different inputs. Then after 5 seconds, it will timeout and then show the next array row. JSfiddle for reference https://jsfiddle.net/sqj3jz4p/
<div>
<label for="votes1">Votes for Candidate 1</label> <input
type="number" class="count" id="votes1" readonly>
</div>
<div>
<label for="votes2">Votes for Candidate 2</label> <input type="number"
class="count" id="votes2" readonly>
</div>
<div>
<label for="votes3">Votes for Candidate 3</label> <input type="number"
class="count" id="votes3" readonly>
</div>
var votingData = {
voting: [
[
336122, 612446, 711326
],
[
4663122, 7001244, 822506
],
[
10437916, 12443910, 930971
],
[
17623004, 18680779, 1060304
],
[
24179347, 21991292, 1175930
]
]
};
function updateVoteCount(array) {
"use strict";
for (var i = 0, l = votingData.voting.length; i < l; i++) {
var voteArray = votingData.voting[i];
console.log(voteArray);
document.getElementById("votes1").value = voteArray[0];
document.getElementById("votes2").value = voteArray[1];
document.getElementById("votes3").value = voteArray[2];
}
}
var timeDelayMs = 5000; // 5-second delay
function voteUpdates(voting,myIndex) {
"use strict";
if ( voting.length > myIndex ) {
updateVoteCount(voting[myIndex]);
setTimeout(voteUpdates, timeDelayMs, voting, myIndex+1);
}
}
voteUpdates(voting[0]);
There were a couple of issues on your code, such as the use of setTimeOut and the parameters for voteUpdates function. Take a look at a version of your code with fixes:
var votingData = {
voting: [
[336122, 612446, 711326],
[4663122, 7001244, 822506],
[10437916, 12443910, 930971],
[17623004, 18680779, 1060304],
[24179347, 21991292, 1175930]]
};
function updateVoteCount(voteArray) {
document.getElementById("votes1").value = voteArray[0];
document.getElementById("votes2").value = voteArray[1];
document.getElementById("votes3").value = voteArray[2];
}
var timeDelayMs = 5000; // 5-second delay
function voteUpdates(voting, myIndex) {
if ( myIndex < voting.length) {
updateVoteCount(voting[myIndex]);
setTimeout(function() { voteUpdates(voting, myIndex+1) }, timeDelayMs);
}
}
voteUpdates(votingData.voting, 0);
<div>
<label for="votes1">Votes for Candidate 1</label> <input
type="number" class="count" id="votes1" readonly>
</div>
<div>
<label for="votes2">Votes for Candidate 2</label> <input type="number"
class="count" id="votes2" readonly>
</div>
<div>
<label for="votes3">Votes for Candidate 3</label> <input type="number"
class="count" id="votes3" readonly>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With