apexprogramming
apexprogramming

Reputation: 433

How to add a setTimeout() to a query selector

I have a JS script

<script>
  document.querySelectorAll('.stylebutton').forEach(function(e) {
  e.addEventListener('click', function() {
    this.style.backgroundColor = 'black';
  })
});
</script>

I want to wait 10 seconds before running. I have tried

<script>
  document.querySelectorAll('.stylebutton').forEach(function(e) {
  e.addEventListener('click', setTimeout(function() {
    this.style.backgroundColor = 'black';
  }),10000)
});
</script>

But I get a console error of can not define this

Upvotes: 1

Views: 608

Answers (1)

Unmitigated
Unmitigated

Reputation: 89394

setTimeout should be invoked inside the callback.

document.querySelectorAll('.stylebutton').forEach(function(e) {
  e.addEventListener('click', function() {
    setTimeout(()=>this.style.backgroundColor = 'black', 10000);
  })
});

Upvotes: 3

Related Questions