Cancelling out a function with a wait time

Hi!

In my game I have a concert stage that plays a random song from a table of different sound IDs. I also have a bell that, when clicked, should cancel/start the music.

function stopMusic()
	playingMusic = false
	music_file:Stop()
	task.wait(math.random(5,15))

	playMusic()
end

function playMusic()
	playingMusic = true

	local value = math.random(1,#music_list)
	local pickedSong = music_list[value]
	local waitTime = time_list[value]
	music_file.SoundId = pickedSong
	music_file:Play()
	task.wait(waitTime)
	stopMusic()
end

function clickedBell()
	if playingMusic == true then
		stopMusic()
	else
		playMusic()
	end
end

remoteEvent.OnServerEvent:Connect(clickedBell)

When a player clicks the bell, the music correctly stops and starts - but the functions continue to run because they were called previously and the songs start and stop abruptly. I need to find a way to cancel out playMusic() and stopMusic() entirely, if that’s even possible. I saw information regarding the Disconnect() function and task.spawn/task.cancel but wasn’t sure how to implement them into my code…

Let me know if I need to provide more info, thanks for any help!

1 Like

Instead of actually cancelling it, maybe you could for example make a variable:

local stopped = false

And in the code, where there’s stopMusic(), before stopping that, do:

if stopped == true then
      stopMusic()
end

Like this, the music won’t stop automatically. I’m not sure if this is the best solution, but if you don’t find any better one, this might be helpful.

3 Likes

Yes, if you were to use threads such as task.spawn and then cancel it would stop the entire function from yielding, however here I think you don’t need to handle all that work and can just use the sound’s respected methods.

example of threads

local thread = task.spawn(function()
    for i=1,10 do
        print(1)
        task.wait(1)
    end
end)

task.wait(3)
task.cancel(thread) 

What you should be doing however

local sound = script.Parent
local chosen

local function play()
     repeat id = music_list[math.random(1,#music_list)] until id ~= chosen
     chosen = id
     sound.SoundId = chosen
     sound:Play()
end

local function pause() -- this is the function you're probably looking for
    sound:Pause()
end

local function resume() -- this is the function you're probably looking for
    sound:Resume()
end

local function stop()
    sound:Stop()
end

play() -- will play a sound
pause() -- will pause the sound
resume() -- will resume the sound
stop() -- will stop the sound

1 Like

I’m really late to answering this, but thank you so much!! This simplifies my code so well, I really appreciate the feedback.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.