0
var coords={100: 100, 120: 120, 140: 140, 160:160, 180:180};

for (var key in coords) {
    console.log(key + ' - ' + coords[key]);
}

I have variable coords and for loop that prints out pairs of numbers like this:

100 - 100

120 - 120

140 - 140

160 - 160

180 - 160

I need setInterval or something to console each pair of numbers every second. I tryed to add setInterval, but in this case the code prints all the numbers every second, not individual pairs.

  • Can you show us how you tried to use `setInterval` in your code please? – Alon Eitan Mar 20 '16 at 20:48
  • var coords={100: 100, 120: 120, 140: 140, 160:160, 180:180}; function getCoord() { for (var key in coords) { console.log(key + ' - ' + coords[key]); } } setInterval(getCoord, 1000); –  Mar 20 '16 at 20:51
  • Hello. I put for loop inside function called getCoor and then called it usind setInterval(getCoord, 1000); But it's not correct logic –  Mar 20 '16 at 20:52

1 Answers1

3

The question is a bit unclear, but I think this is what you are asking for. It will print the first pair, wait, print the next pair, wait, and so on.

var coords = {/* coords */};
var keys = Object.keys(coords);
var index = 0;

var interval = setInterval(function() {
    console.log(keys[index] + " - " + coords[keys[index]]);
    index++;
    if(index == keys.length) {
        clearInterval(interval);
    }
}, 3000);

As a side note, the order of values in Javascript objects are not guaranteed. If the order you print the coordinates matters or even if coordinates actually represents a list of coordinates, it would be better to make coordinates an array of pairs of numbers instead of an object. Additionally, the keys of the object are converted to strings, which is something you do not want with numerical coordinates.

Community
  • 1
  • 1
afuous
  • 1,448
  • 10
  • 11