This code is doesn't work correctly sync the idle animation correctly. [Need Help]

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Trying to make the animations sync to the beat of the music.

  2. What is the issue? The Code Play The Animation more then once every bps*2

  3. What solutions have you tried so far? I changed some code around tho I haven’t found a fix.

So this code below is suppose to help sync the idle animation with the beat of the music

local bps = 60 / 156
local function playAnimationForDuration(animationTrack, duration, id)
	if Started then
		local activeTracks = humanoid:GetPlayingAnimationTracks()
		for _,v in pairs(activeTracks) do
			v:Stop()
		end

		animationObject.AnimationId = id
		animationTrack = humanoid.Animator:LoadAnimation(animationObject)

		local speed = animationTrack.Length / duration
		animationTrack:AdjustSpeed(speed)
		animationTrack:Play()
	end
end

-- Play idle animation every bps*2
task.spawn(function()
	while true do
		if IsIdle then
			playAnimationForDuration(animationTrack,bps,idle)
		end
		task.wait(bps*2)
	end
end)