I wanted to write a simple script to mimic a typewriter typing The Shining’s “All work and no play” lines. I wrote it in python first, but then decided to re-write it in JavaScript. The Python is more complex than it needs to be, but I wanted to practice generators.
All work and no play
Python:
- #!/usr/bin/env python3
- import time
- import random
- jack = "All work and no play makes Nick a dull boy. "
- PROB_SKIP = 0.01
- def sometimes(percent=0.50):
- return random.random() < percent
- def all_work():
- while True:
- for c in jack:
- if sometimes(PROB_SKIP):
- continue
- yield c
- time.sleep(0.050)
- time.sleep(0.400)
- if __name__ == '__main__':
- for work in all_work():
- print("{work}".format(work=work), end=" ", flush=True)
Javascript:
- function typer(text, n) {
- if (n < (text.length)) {
- document.getElementById("typer").innerHTML = text.substring(0, n++);
- setTimeout(function() { typer(text, n) }, 100);
- }
- }