1

As a result of another function, i have a JSON object saved in a variable 'json_result'.

My goal is to console.log every JSON-PART (e.G. json_result[i]) after a timeout of 5 seconds.

My first try looked like this:

for (let key in json_result) {
setTimeout(() => {
if(json_result.hasOwnProperty(key)) {
    console.log(key + " -> " + JSON.stringify(json_result[key]));
 };
 },5000);
 };

Even though i used the 'let' keyword for scoping, its not working.

My second approach tried to outsource the settimeout-functionality:

for (let key in json_result) {
setTimeout(() => {
if(json_result.hasOwnProperty(key)) {
    delayer(key);
 };
 },5000);
 };

function delayer(i) {
    setTimeout(() => { console.log(i + "->" + JSON.stringify(json_result[i]));}, 5000)};

Does somebody has an explanation why this doesnt work and can provide a solution?

Best regards

Jimbo.Koen
  • 151
  • 10

1 Answers1

0

You likely want this

const json_result = {
  "keyA": "valueA",
  "keyB": "valueB",
  "keyC": "valueC"
}


const keys = Object.keys(json_result)
cnt = 0;
const show = () => {
  console.log(keys[cnt] + " -> " + JSON.stringify(json_result[keys[cnt]]));
  cnt++;
  if (cnt < keys.length) setTimeout(show, 5000);
};
show();
mplungjan
  • 169,008
  • 28
  • 173
  • 236