Problem of the Day
A new programming or logic puzzle every Mon-Fri

Debounce

Sometimes when writing code you need to run a certain function in a loop. However, that function may need to make database calls or do some other sort of expensive computation. To prevent that call from happening you can debounce the function or essentially limit how often it runs. Today's goal is to create a debouncer that only lets a function run at most 4 times per second. The functionality should be similar to this:

count = 0;

while(true) {
    debounce(function() {
        count++;
    }, 250);
}

Permalink: http://problemotd.com/problem/debounce/

Comments:

  • Anonymous - 10 years, 1 month ago

    C# with simple console app to test results

    class Program
    {
        private static int count = 0;
    
        static void Main(string[] args)
        {
            int x = 100;
            Console.WriteLine("Testing debouncer, method will run {0} times.", x);
    
            Debouncer(PrintCount, x);
    
            Console.WriteLine("\nPress Any Key To Exit");
            Console.ReadKey();
        }
    
        private static void PrintCount()
        {
            Console.WriteLine("{0} {1}", count.ToString(), DateTime.Now.ToString("hh:mm:ss.ff"));
            count++;
        }
    
        private static void Debouncer(Action method, int runCount)
        {
            for(int i = 0; i < runCount; i++)
            {
                method();
    
                Thread.Sleep(250);
            }
        }
    }
    

    reply permalink

Content curated by @MaxBurstein