Yêu cầu thg 9 19, 2023 6:01 SA 127 0 1
  • 127 0 1
0

Lối loop khi sử dụng setInterval

Chia sẻ
  • 127 0 1

Chào mọi người. Mình có rắc rối khi dùng javascript Mình có file javascript sau

import { Controller } from '@hotwired/stimulus'

const SOUND = 'https://daveceddia.com/freebies/react-metronome/click1.wav'

export default class MetronomeController extends Controller {
  static targets = ['bpm', 'tempoButton']

  connect() {
    this.bpm = parseInt(this.bpmTarget.value)
    this.playing = false
    this.tempoButtonTarget.textContent = this.tempoButtonTarget.innerHTML
    this.beat = new Audio(SOUND)
  }

  handleClick() {
    this.playing = !this.playing

    if (this.playing) {
      this.start()
    } else {
      this.stop()
    }
  }

  start() {
    console.log(this.bpm)
    this.timer = setInterval(this.beat.play(), (60 / this.bpm) * 1000)
    this.tempoButtonTarget.textContent = 'Stop metronome for the song'
  }

  stop() {
    clearInterval(this.timer)
    this.tempoButtonTarget.textContent = 'Start metronome for the song'
  }
}

Và ở phía HTML, mình gọi

<div data-controller="metronome"><input data-metronome-target="bpm" placeholder="BPM" type="hidden" value="185">
    <button name="button" type="button" data-action="metronome#handleClick" class="btn btn-primary">
        <span data-metronome-target="tempoButton">Start metronome for the song</span>    
    </button>
</div>

Tuy nhiên thay vì gọi được tiếng tick tick thì mình gặp được 1 chuỗi các error log như ở ảnh gif:

268044182-8e97c137-f9f2-4113-9862-3b638b85c736.gif

Các bạn giúp đỡ mình với các bạn ơi

1 CÂU TRẢ LỜI


Đã trả lời thg 9 19, 2023 6:14 SA
by Dev Success 101
Đã được chấp nhận
+2

Khả năng lỗi do dòng này nè em:

this.timer = setInterval(this.beat.play(), (60 / this.bpm) * 1000)

Cái argument đầu tiên phải là một function để nó thực thi trong mỗi lần lặp. Còn trong code kia thì tại dòng setInterval cái hàm play nó đã chạy luôn mất rồi. Em sửa lại kiểu như sau:

this.timer = setInterval(this.beat.play.bind(this.beat), (60 / this.bpm) * 1000);

// hoặc thế này:
this.timer = setInterval(() => this.beat.play(), (60 / this.bpm) * 1000);

https://developer.mozilla.org/en-US/docs/Web/API/setInterval

Chia sẻ
Avatar Hoàng Đức Quân @devil_boom_129
thg 9 19, 2023 7:26 SA

đúng thật em thử chưa kỹ. em lại chạy theo cái syntax này setInterval(code, delay). thanks anh

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí