Skip to content

Instantly share code, notes, and snippets.

@spiechu
Created January 7, 2013 22:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spiechu/4479209 to your computer and use it in GitHub Desktop.
Save spiechu/4479209 to your computer and use it in GitHub Desktop.
Gist is a part of blog entry at http://spiechu.pl/2013/01/07/pierwsze-kroki-z-dart/ [in Polish] Working version can be found at http://spiechu.pl/dart/num_counter.html
import 'dart:isolate';
import 'dart:html';
/**
* Isolate running asynchronously.
*/
void numCounter() {
port.receive((msg, replyTo) {
Element h1 = query("h1#counter${msg['id']}");
int counter = 0;
int currentNumber = 0;
new Timer.repeating(25, (Timer timer) {
if (currentNumber > 9) {
currentNumber = 0;
}
h1.text = currentNumber.toString();
currentNumber++;
counter++;
if (counter > msg['counter']) {
timer.cancel();
h1.text = msg['number'];
replyTo.send(msg['number']);
}
});
});
}
/**
* Script entry point.
*/
void main() {
Element submitInput = query('input#submit');
Element errorBox = query('span#errorbox');
Element countersDiv = query('div#counters');
submitInput.on.click.add((e) {
errorBox.text = '';
countersDiv.text = '';
HTMLInputElement inputNumbers = query('input#numbers');
String inputtedNumbers = inputNumbers.value;
List<String> numbers = inputtedNumbers.splitChars();
bool hasErrors = false;
numbers.forEach((element) {
try {
int.parse(element);
} on FormatException {
hasErrors = true;
print('element $element is not an integer');
}
});
if (hasErrors) {
errorBox.text = 'Wpisz same cyfry!';
}
else {
for (num i = 1; i <= numbers.length; i++) {
HeadingElement h1 = new HeadingElement.h1();
h1.id = 'counter$i';
h1.text = '0';
countersDiv.append(h1);
}
List<SendPort> spawned = new List<SendPort>();
num timeout = 20;
num firstId = 1;
numbers.forEach((item) {
SendPort sender = spawnFunction(numCounter);
sender.call({
'number' : item,
'counter' : timeout,
'id' : firstId
}).then((String res) => print('result was: [$res]'));
spawned.add(sender);
timeout += 10;
firstId += 1;
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment