Repeating a function every few seconds

Use a timer. There are 3 basic kinds, each suited for different purposes. System.Windows.Forms.Timer Use only in a Windows Form application. This timer is processed as part of the message loop, so the the timer can be frozen under high load. System.Timers.Timer When you need synchronicity, use this one. This means that the tick event …

Read more

How to break outer cycle in Ruby?

Consider throw/catch. Normally the outside loop in the below code will run five times, but with throw you can change it to whatever you like, breaking it in the process. Consider this perfectly valid ruby code: catch (:done) do 5.times { |i| 5.times { |j| puts “#{i} #{j}” throw :done if i + j > …

Read more

Please explain the use of JavaScript closures in loops [duplicate]

WARNING: Long(ish) Answer This is copied directly from an article I wrote in an internal company wiki: Question: How to properly use closures in loops? Quick answer: Use a function factory. for (var i=0; i<10; i++) { document.getElementById(i).onclick = (function(x){ return function(){ alert(x); } })(i); } or the more easily readable version: function generateMyHandler (x) …

Read more

Iterate a certain number of times without storing the iteration number anywhere [duplicate]

The idiom (shared by quite a few other languages) for an unused variable is a single underscore _. Code analysers typically won’t complain about _ being unused, and programmers will instantly know it’s a shortcut for i_dont_care_wtf_you_put_here. There is no way to iterate without having an item variable – as the Zen of Python puts …

Read more