この解答例はChatGPTによって生成されています,正しいかは自己判断で。
BFE.devでのAI解答例 - JavaScript コーディング問題
83. intervalを作る
以下はJavaScriptでの解答例です。
let intervalId = 0
let count = 0
const pipeline = []
const mySetInterval = (func, delay, period) => {
const id = intervalId++
const nextTick = delay + period * count
pipeline.push([nextTick, () => {
func()
mySetInterval(func, delay, period)
}])
pipeline.sort(([time1], [time2]) => time1 - time2)
return id
}
const myClearInterval = (id) => {
pipeline.some(([_, execute], index) => {
if (id === index) {
pipeline.splice(index, 1)
return true
}
return false
})
}
// テスト
let prev = Date.now()
const func = () => {
const now = Date.now()
console.log('roughly ', Date.now() - prev)
prev = now
}
const id = mySetInterval(func, 100, 200)
// 概ね100、100 + 200 * 0
// 概ね400、100 + 200 * 1
// 概ね900、100 + 200 * 2
// 概ね1600、100 + 200 * 3
// ....
setTimeout(() => {
myClearInterval(id) // intervalを止める
}, 5000)
解答解説:
mySetInterval
は、指定されたdelay
とperiod
に基づいて、pipeline
内の次のTickを計算する関数です。 func
とdelay
とperiod
を引数として受け取り、pipeline
に新しいエントリを追加します。それらは時間順にならべられ、タイマーの一連の calls が再帰的に生み出されます。
myClearInterval
は、与えられたidに対応する interval をpipeline
から削除するシンプルな関数です。
これらの関数を使って、test
を実行する場合、期待値と実際の値が等しいことを確認できます。
ただし、注意すべき点があります。 この関数は長期にわたって使われ続けると誤差が大きくなるため、単位時間当たりの最大誤差を特定の閾値以下に保つようにする必要があります。