我有一個類似的問題,因爲setInterval
不能依靠「長時間保持時間」。我的解決方案是下面的代碼片段:(在咖啡腳本中,編譯好的js在最後的鏈接中)
它提供了一個替代setInetrval的下拉菜單,它將保持非常接近的時間。有了它,你可以這樣做:
accurateInterval(1000 * 60/bpm, callbackFunc);
見我的使用情況和例子同步使用提供的BPM視覺效果到YouTube的視頻在這裏:http://squeegy.github.com/MandalaTron/?bpm=64&vid=EaAzRm5MfY8&vidt=0.5&fullscreen=1
accurateInterval代碼:
# Accurate Interval, guaranteed not to drift!
# (Though each call can still be a few milliseconds late)
window.accurateInterval = (time, fn) ->
# This value is the next time the the timer should fire.
nextAt = new Date().getTime() + time
# Allow arguments to be passed in in either order.
if typeof time is 'function'
[fn, time] = [time, fn]
# Create a function that wraps our function to run. This is responsible for
# scheduling the next call and aborting when canceled.
wrapper = ->
nextAt += time
wrapper.timeout = setTimeout wrapper, nextAt - new Date().getTime()
fn()
# Clear the next call when canceled.
wrapper.cancel = -> clearTimeout wrapper.timeout
# Schedule the first call.
setTimeout wrapper, nextAt - new Date().getTime()
# Return the wrapper function so cancel() can later be called on it.
return wrapper
GET咖啡腳本和js在這裏:https://gist.github.com/1d99b3cd81d610ac7351
雖然沒有真正回答這個問題。你或許可以準確地掌握節奏,但是由於音樂需要一些未知時間才能加載,所以你會在一段固定的時間內關閉;我不認爲有一個確定的方法可以知道音樂什麼時候開始播放。 –