Task.cancel() and/or task.delay() causing crash

hello so i seem to be having a weird issue

this is the code that crashes studio as shown in the video below:

	local shield = Instance.new("DoubleConstrainedValue")
	shield.MaxValue = 250
	shield.Value = 0
	shield.Name = "Shield"
	shield.Parent = character
	
	local lastChanged = nil
	local shieldEvent = shield.Changed:Connect(function(a)
		if lastChanged then
			task.cancel(lastChanged)
		end
		
		
		lastChanged = task.delay(4,function()
			shield.Value = 0
			if lastChanged then lastChanged = nil end 
		end)
		
	end)

heres the video:

and heres the code that doesnt crash as shown in the second video:

	local shield = Instance.new("DoubleConstrainedValue")
	shield.MaxValue = 250
	shield.Value = 0
	shield.Name = "Shield"
	shield.Parent = character
	
	local lastChanged = nil
	local shieldEvent = shield.Changed:Connect(function(a)
		print("all good")
		--[[if lastChanged then
			task.cancel(lastChanged)
		end
		
		
		lastChanged = task.delay(4,function()
			shield.Value = 0
			if lastChanged then lastChanged = nil end 
		end)]]
		
	end)

not sure if am i writting something incorrectly any help appreciated yea

Maybe take a look at Roblox’s Function Library For task.

From there, you can actually see that there isn’t a task.cancel/task.delay on the task library. Which means, maybe instead you should use a different way of whatever your code is doing.

If they still show up for you in the script editor, then maybe what I’ve said could be wrong. It can be that LastChanged is being changed after your cancelling it. So, what that mean is to change this:

if lastChanged then
			task.cancel(lastChanged)
		end
		
		
		lastChanged = task.delay(4,function()
			shield.Value = 0
			if lastChanged then lastChanged = nil end 
		end)

To this:

		lastChanged = task.delay(4,function()
			shield.Value = 0
			if lastChanged then lastChanged = nil end 
		end)

        if lastChanged then
			task.cancel(lastChanged)
		end

wouldnt that immediatly cancel the function above though

add-on not sure what you meant isnt in the library, ive used task.cancel/delay() in alot of my other code it never crashed

This was already reported: Task.cancel crash game and studio

The official task library docs don’t list a task.cancel though, so maybe it isn’t fully released and stable?

oh shoot that did not pop up in my google search, oopsies, alright thx

Relooking at it, yeah it would. poorly scripted.