EasyTimer - JavaScript style setTimeout and setInterval in C#

I found JavaScript setTimeout and setInterval functions quite handy for timer like functionality and some time wish I could use that in C# too. In an earlier post I create a C# like timer functionality in JavaScript. Now, I want to do opposite i.e. implement JavaScript setTimeout and setInterval like functionality in C#.

This is can be done very easily using Lamda expressions and Timer. Look at the below utility class -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DailyCoding.EasyTimer
{
    public static class EasyTimer
    {
        public static IDisposable SetInterval(Action method, int delayInMilliseconds)
        {
            System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
            timer.Elapsed += (source, e) =>
            {
                method();
            };

            timer.Enabled = true;
            timer.Start();

            // Returns a stop handle which can be used for stopping
            // the timer, if required
            return timer as IDisposable;
        }

        public static IDisposable SetTimeout(Action method, int delayInMilliseconds)
        {
            System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
            timer.Elapsed += (source, e) =>
            {
                method();
            };

            timer.AutoReset = false;
            timer.Enabled = true;
            timer.Start();

            // Returns a stop handle which can be used for stopping
            // the timer, if required
            return timer as IDisposable;
        }
    }
}

To use setTimeout this you can simply do -

EasyTimer.SetTimeout(() =>
{
    // --- You code here ---
    // This piece of code will once after 1000 ms delay

}, 1000);

The code will run after 1000 ms delay similarly like JavaScript setTimeout. The function also returns a handle. If you want clearTimeout like functionality, then the simply dispose off the handle.

var stopHandle = EasyTimer.SetTimeout(() =>
{
    // --- You code here ---
    // This piece of code will once after 1000 ms

}, 1000);

// In case you want to clear the timeout
stopHandle.Dispose();

Similarly you can use setInterval as -

EasyTimer.SetInterval(() =>
{
    // --- You code here ---
    // This piece of code will run after every 1000 ms

}, 1000);

and SetInterval also returns a stop handle which you can use for clearInterval like functionality. Just dispose off the handle -

var stopHandle = EasyTimer.SetInterval(() =>
    {
        // --- You code here ---
        // This piece of code will run after every 1000 ms
        // To stop the timer, just dispose off the stop handle

    }, 1000);

// In case you want to clear the interval
stopHandle.Dispose();

10 comment(S)


Faisal on Jan 1, 2013 12:04 AM

Excellent code snippet. I must say, quite handy in fact.
Thanks dear, you solved my issue what I was looking for on web.

udidu on Jan 29, 2013 02:30 AM

Great! exactly what I needed!

Dan on Feb 4, 2013 11:22 AM

Does this actually let other code run while it's in use, or does it need to be created in a background worker/thread? (I'm kinda noob-ish here, to non-web C# coding, sorry) It seems to make the whole program wait until its timeout has finished.

aquari on Feb 11, 2013 01:04 PM

actually i'm trying to do a online exam...
in that i want use timer for automatic submitting of answers after completion of time... and score should display in a pop-up message...........

Any on Apr 11, 2013 07:50 PM

Hey, I want to use your code for a no-commercial project. I wanted to give credits to you by adding in the code comments the address of this website and the author name, but I couldn't find your name.

derVerzweifler on May 17, 2013 05:25 AM

Yeah! Thanks!

ozlusozlertr on Jul 15, 2013 06:30 AM

that helped me a lot

FunctionalCAT on Jul 21, 2013 01:33 PM

Hi there!

Very common pattern indeed. Have you looked at The Reactive Framework? Observable.Timer() provides the timer functionality for you. For example, you could rewite your EasyTimer methods as

public static IDisposable SetInterval(Action method, TimeSpan delay)
{
return Observable.Timer(dueTime: delay).Subscribe(_ => method());
}

public static IDisposable SetTimeOut(Action method, TimeSpan delay)
{
return Observable.Timer(dueTime: delay, period: delay).Subscribe(_ => method());
}


You can also have a SetTimeOut overload that specifies time elapsed before the first trigger (essentially dueTime).

Cheers!

brad parks on Oct 29, 2013 07:12 AM

nice! very useful to just set it and forget it!

sponsored

Fl0zZa on Dec 21, 2013 01:16 PM

Thanks man
If any of you encounter the thread owning problem like me, just use DispatchTimer instead of Timer class, for example for Timeout method :

DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(delayInMilliseconds);
timer.Tick += (source, e) =>
{
method();
timer.Stop();
};
timer.Start();


Leave a comment