Search code examples
javascriptfunctional-programminglodashyarnpkg

How to print something in delay in Lodash


I have an exercise in JS/Lodash to print ten songs in delay of 5 seconds each. The problem is, that I get 10 times the song, that index is 14th. I don't know where I made a mistake, would be grateful for any help.

const utwory = [{
    "author": "Queen",
    "song": "Bohemian Rhapsody",
    "place": 1,
    "change": 0
  },
  {
    "author": "Deep Purple",
    "song": "Child in time",
    "place": 2,
    "change": 2
  }
]

function ex7() {
  let i = 0;


  while (i < 10) {
    _.delay(function(arr) {
      console.log(arr[i].author + " " + arr[i].song)
    }, 10000, utwory)

    i += 1
  }
}
ex7()



    
   

Solution

  • When the function inside the _.delay() is invoked, it uses the current value of i, which is 10. You can solve it by changing the loop to a for loop, and use let i, so i would the it's value inside the closure.

    In addition, you can avoid this problem by passing the current item utwory[i] to the delay, and just console.log() the item in the callback.

    I've used both methods here:

    const utwory = [{"author":"Queen","song":"Bohemian Rhapsody","place":1,"change":0},{"author":"Deep Purple","song":"Child in time","place":2,"change":2}]
    
    function ex7() {
      for(let i = 0; i < utwory.length; i++) {
        _.delay(function({ author, song }) {
          console.log(`${author} ${song}`)
        }, 1000 * (i + 1), utwory[i]) // set the item to print here
      }
    }
    
    ex7()
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"></script>