Search code examples
javascriptsettimeout

For loop with setTimeout?


I have a function that shows me all from object.

queries = {
  "info": {
    "query": "SELECT ...",
    "id": "10"
  },
  "info2": {
    "query": "INSERT ...",
    "id": "12"
  },
  "infoN": {
    "query": "DELETE ...",
    "id": "123"
  }
}

for (var [key, value] of Object.entries(queries)) {
    let name = key;
    let query = value.query;
    let id = value.id;

    console.log(name);
    console.log(query);
    console.log(id); 
    //setTimeout(function() { }, 3000);
}

But I need to to show first object and after 3 sec another and so on. How can I loop them with setTimeout? Or something similar?


Solution

  • The simplest way is to just use a different delay in each call of setTimeout

    let counter = 1
    for (...){
        setTimeout(function() { }, 3000 * counter++);
    }
    

    Since Object.entries returns an Array, we could also use Arrray.entries to get a iteration counter in the for statement.

    queries = {
      "info": {
        "query": "SELECT ..."
      },
      "info2": {
        "query": "INSERT ..."
      },
      "infoN": {
        "query": "DELETE ..."
      }
    }
    
    for (let [counter, [key, value]] of Object.entries(queries).entries()) {
      const delay = (counter + 1) * 1000
      setTimeout(() => {
        console.log({
          counter,
          delay,
          key,
          value
        })
      }, delay)
    }

    Though I think setting counter directly is just as easy to read.