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 –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 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 –
1 2 3 4 5 6 7 8 | 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.
1 2 3 4 5 6 7 8 9 10 11 | 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 –
1 2 3 4 5 6 7 8 | 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 –
1 2 3 4 5 6 7 8 9 10 11 12 | 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(); |