+ 1

How to delay an action using timer?

Im trying to slowly draw a grid ( cell by cell ). I tried to make a timer which increments "ticks" variable and then put "if(ticks % 10 == 0)" inside of for loop but it will skip cells. How can i pause the "for" loop with a timer? Piece of code: private void timer1_Tick(object sender, EventArgs e) { tick++; Text = tick.ToString(); } private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (tick % 10 == 0) g.DrawRectangle(Pens.Red, i * h, j * w, h, w); } } }

5th Dec 2022, 5:37 PM
Artur
Artur - avatar
4 Answers
+ 3
Sure, you are right. Timer can be used. For some reason I thought your question was about JavaScript, so ignore my previous comment. https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/run-procedures-at-set-intervals-with-wf-timer-component?view=netframeworkdesktop-4.8
5th Dec 2022, 7:35 PM
Tibor Santa
Tibor Santa - avatar
+ 1
You can use the setTimeout() function to introduce delayed actions in the browser's event loop. It is a bit tricky though, there are a few gotchas. There is also the delay() function in jQuery but with more limited usage. https://www.sitepoint.com/javascript-settimeout-function-examples/ https://www.sitepoint.com/delay-sleep-pause-wait/
5th Dec 2022, 6:43 PM
Tibor Santa
Tibor Santa - avatar
+ 1
Tibor Santa thank you, gonna try it tommorow
5th Dec 2022, 7:37 PM
Artur
Artur - avatar
0
Tibor Santa is there any way to do this only with WinForm? For example in python(pygame) you can set tick-rate for whole program or use delta time, is it possible to achieve the same result with Timer from winform?
5th Dec 2022, 7:23 PM
Artur
Artur - avatar