Ruby Logo

Ruby: Debounce utility function

require 'timeout' ⏎

def debounce(wait)
	return proc do |&block|
		last_call = 0
		timer = nil
		proc do |*args, &inner_block|
			current_time = Time.now.to_f
			if timer
				timer.shutdown
			end
			if current_time - last_call >= wait
				last_call = current_time
				block.call(*args, &inner_block)
			else
				timer = Timeout::timeout(wait - (current_time - last_call)) do
					block.call(*args, &inner_block)
				end
			end
		end
	end
end
Accuracy
100 %
0 Mistakes
CPM
0
Average: 0 CPM
Time
0.000 s
Personal best: -.--- s