I got tired of starting timer every time I need to do something simple as running some function 5 seconds after something in my code happens. So I tried to write a function (actually, 3 of them: setTimeout
, setInterval
and clearInterval
) to write one line of code when I need it instead of, say, five.
It is working, at least for the cases I tested.
I understand that maybe something in that code is not right, maybe I forgot about something. Should I improve anything in my approach?
using System;
using System.Windows.Forms;
namespace timeouts_test
{
public partial class Form1 : Form
{
private Timer[] timerList = new Timer[100];
private int timerMaxIndex = -1;
public Form1()
{
InitializeComponent();
int aInterval = SetInterval(500, a);
int bInterval = SetInterval(500, b);
int cInterval = SetInterval(500, c);
SetTimeout(3500, () =>
{
ClearInterval(aInterval);
});
SetTimeout(7000, () =>
{
ClearInterval(bInterval);
});
SetTimeout(10500, () =>
{
ClearInterval(cInterval);
});
}
public void a()
{
label1.Text += "a";
}
public void b()
{
label1.Text += "b";
}
public void c()
{
label1.Text += "c";
}
public int SetInterval(int time, Action function)
{
Timer tmr = new Timer();
tmr.Interval = time;
tmr.Tick += new EventHandler(delegate (object s, EventArgs ev)
{
function();
});
tmr.Start();
timerMaxIndex++;
var index = timerMaxIndex;
timerList[timerMaxIndex] = tmr;
return index;
}
public int SetTimeout(int time, Action function)
{
Timer tmr = new Timer();
tmr.Interval = time;
tmr.Tick += new EventHandler(delegate (object s, EventArgs ev)
{
function();
tmr.Stop();
});
tmr.Start();
timerMaxIndex++;
var index = timerMaxIndex;
timerList[timerMaxIndex] = tmr;
return index;
}
public void ClearInterval(int interval)
{
if (timerList[interval] == null)
return;
timerList[interval].Stop();
timerList[interval] = null;
if (interval == timerMaxIndex)
timerMaxIndex--;
}
}
}
(Functions a
, b
and c
were made just to test this.)