DailyCoding > General

EasyTimer - JavaScript style setTimeout and setInterval in C#

how to implement and use JavaScript style setTimeout and setInterval in C#
Author admin on Oct 3, 2012 6 Comments
Rate it    (Rated 4 by 14 people)
3,713 Views

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();

C# | Javascript | Utility
 

Discussion

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!

Leave a Comment

Name
Email Address
Web Site