...is not a function

Below is part of my method where I get errors playSong is not a function. How can I call it inside setTimeout?

methods: {

        playSong(src, currentItem){
          
          //......

           setTimeout(function(src, item){
               this.playSong(src, item)      //<<-------Uncaught TypeError: this.playSong is not a function
           }, this.duration);
        }

}

1 Like

this inside your setTImeout function is not what you think it is. This is a common pattern with Javascript and a common “Gotcha”. Best to read up this part of the language, and why this happens, and what to do about it. But here are two ways.

var self = this
setTimeout(function(src, item) {
   self.playSong(src,item)
}, this.duration)

or if you’re using ES2015 syntax, fat arrow functions preserve this and is a welcomed feature of that syntax.

setTimeout ((src, item) => {
   this.playSong(src, item)
}, this.duration)
4 Likes

To add to @bolerodan’s comment about the setTimeout being called off window.setTimeout therefore pointing to window…

Here’s another way to pass in a method to setTimeout while maintaining this pointer.

window.setTimeout( this.playSong.bind(this), this.duration)

bind is great for “exporting” functions while keeping their path. Another fun example…

const log = consoe.log.bind(console)

2 Likes

Thank you guys for helping me out!

1 Like