Skip to content

Instantly share code, notes, and snippets.

@CipherLab
Created July 11, 2014 15:12
Show Gist options
  • Save CipherLab/10a40f7032be04f0aa6f to your computer and use it in GitHub Desktop.
Save CipherLab/10a40f7032be04f0aa6f to your computer and use it in GitHub Desktop.
Javascript style interval/timeout in c#
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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment