How to loop something, and break the loop when button is pressed again

So i’m doing a radio system with a button. For now my script is working phenomenally.

However now comes the hard part:

I want to make a loop that basically tweens a static sound in a loop, WHILE the radio is on.

the idea is that the tween turns the static volume from 0 to 0.3 real fast and has a true property so it goes back to 0 after completing.

The way I made it random is with math.random.

Now, I basically want to make this randomness loop, so it can happen randomly while the radio is on, at any time.

I tried using a while task.wait(1) do loop but the problem is that it would just get stuck in that loop and the radio couldn’t be switched off.

So, any ideas?

It’s hard to know what would work without seeing the code for how you set up the radio.

Have you tried doing this in a separate thread using either task.spawn or task.defer?

1 Like

So basically, task.spawn is literally a way to make code run parallel to each other?

so is this like making some parts of code “side missions”, like so the script doesn’t wait for it to finish, but it runs parallel to the main script?

Short answer: yes

Long answer:
Depends on what you mean by in parallel. If you define parallel as two separate contexts running independent of each other, then yea. If you define parallel as code running simultaneously, then no.

task.spawn will immediately yield the calling code and run the function you used in task.spawn. No other code will run until that function completes or yields (e.g., task.wait). So in a sense, it may look like two pieces of code are running separately whereas in reality, they are more so passing control back and forth to each other.

You can see the behavior with the following script

task.spawn(function()
    print("Inside task.spawn")
    for i = 1, 10 do
        print("spawn:", i)
    end
end)

print("Outside task.spawn")
for i = 1, 10 do
    print(i)
end

If you run this, you’ll notice that the loop inside task.spawn will run to completion before “Outside task.spawn” even gets printed.

Inside task.spawn
spawn: 1
spawn: 2
...
spawn: 10
Outside task.spawn
1
2
...
10

However, if you introduce task.wait inside the task.spawn function

task.spawn(function()
    print("Inside task.spawn")
    for i = 1, 10 do
        print("spawn:", i)
        task.wait()
    end
end)

The output should look something like

Inside task.spawn
spawn: 1
Outside task.spawn
1
2
...
10
spawn: 2
spawn: 3
...

Because you called task.wait, you sort of give up control of that thread and allow other threads to continue running until they complete or yield.

I make this distinction because Roblox does have an API for multithreading which actually does have code running simultaneously.

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