Check if value changes under certain time

Hello!
I’m trying to make a script, where if the BoolValue’s value changes to true, and it doesn’t change to false in 20 seconds, then it would be set to false manually by the script.

I tried smth like this:

BoolValue.Changed:Connect(function(val)
    if val == true then
        wait(20)
        if BoolValue.Value == true then
            BoolValue.Value = false
        end
    end
end)

but it doesn’t work, it doesnt stop the function if the BoolValue changes to false.

I tried also disconnecting the connection when the value changed to false, but that got complicated and it still didn’t fix it. D:

Can anyone help?

If it’s going to be set to false either way, why not just skip the if check?

because theres a process that happens sometimes, where the value changes to true, and then changes back to false in 3-6 secs. But rarely, it breaks, and sets the value to true without changing it back.
Basically it could set another process’ value to false early.

local function Check()
if BoolValue.Value then task.wait(20) BoolValue.Value = false end
end)

BoolValue.Changed:Connect(Check)
local Counter = 0

BoolValue.Changed:Connect(function(val)
Counter += 1
if Counter <= 5 then -- For example (5) in this case
--YOUR CODE -- If the bool has been changed less then your number of times
else
--YOUR CODE -- if the bool changes over (5) times this code here runs
end
end)

is this what your looking for?
Sorry i miss red completely

Not really, thats counting how many times the function fired.

What i wanna achieve is to change the value to false in 20 seconds, if it doesnt change while waiting.

Just use :Once() this makes sure that the function can only happen once, It will only run The First time Your bool value is changed and Never Again, This way you dont need to worry about disconnecting it

if this helped please mark it as The answer, i would appreciate it


BoolValue.Changed:Once(function()
if BoolValue.value == true then
task.wait(20)
if BoolValue.value == true then
BoolValue.Value = false
end
end
end)
1 Like
local boolValue = yourbool
local tracker = nil

boolValue.Changed:Connect(function(new)
      if new == true then
          tracker = task.delay(20,function()
              if boolValue.Value == true then
                  boolValue.Value = false
              end
          end)
      else if new == false and tracker ~= nil then
           task.defer(task.cancel,tracker)
      end
end)

is this what you mean?

1 Like

Omg yeah, thank you so muchh =D

1 Like

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