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();
12 comment(S)