Start an event and stop when you click again - chromeExtension

Asked

Viewed 50 times

1

I’m creating a very simple extension in Chrome for Whatsapp Web to speed up the audio by 1.5x, but so far I’ve only been able to make the function run, and it keeps running until the page is reloaded. I’m trying to make sure that when I click again, the event stops and the audio returns to normal speed. But I don’t know how to end this event. Should I use async/await? Promises?

const interval = setInterval(() => {
   const header = document.querySelector('._1QUKR')
   if (header) {
      console.log(header)
      clearInterval(interval)

      const button = document.createElement("button")
      button.innerHTML = '1.5'
      button.classList.add('twoTimesButton')

      button.addEventListener('click', () => {
         const audios = document.querySelectorAll('audio')
         console.log(audios)
         audios.forEach((audio) => {
            console.log(audio)
            audio.playbackRate = 1.5
         })

      button.addEventListener('click', function() {
         audios.pause()
      })   
      })

      header.appendChild(button)
   }
}, 1000)

I’m starting my studies in Javascript and I’ve already taken a good look at what there is of question here and I’ve seen a topic that really seems to be something very similar to what I’m needing, but I just couldn’t implement the same logic.

1 answer

1

Seeing your code, I saw that you created a new button called button, where when clicked, the audios get the speed of 1.5x

You could create two buttons, where one button could take the current audio playbackRate and reduce by 0.1, for example, and the other button would do the exact opposite, increasing the playbackRate by 0.1, this would be enough to solve your problem.

For this, just create the buttons in the same way, add a click eventListener and do the action.

document.querySelectorAll("audio").forEach(audio => audio.playbackRate += 0.1)

If you want to "reset" the playbackRate to normal speed using the same button, when performing the click action, you can do a validation, and if the playbackRate is different from 1, which means that it has been changed, you return it to the desired value.

audio.forEach(() => {
 if (audio.playbackRate != 1)
    audio.playbackRate = 1
});
  • I implemented the changes and became really cool. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.