Stimulus Discourse

setTimeout in Stimulus


#1

I understand this is more a JS-related question than Stimulus-specific but can anyone explain to me why this works

connect() {
  setTimeout(() => this.hideButton(), 1000)
}

while this fires HideButton without delay?

connect() {
  setTimeout(this.hideButton(), 1000)
}

I needed to set some delay and tried the second snippet without success. After searching for hints I came across Can't load child controller by target which pointed me in the right direction.

But now, I’d like to understand why.

Thanks


#2

setTimeout expects a function and milliseconds time as arguments. In your first example, you’re creating an anonymous function and passing it in–which is correct. In your second example, you’re not passing in a function.

this.hideButton is a function, this.hideButton() is whatever is returned from calling this.hideButton(). So, basically just remove the () in your second example.


#3

Thanks for the explanation.