patternjavascriptMinor
Count to target with JavaScript
Viewed 0 times
withcountjavascripttarget
Problem
I'm looking for (and be as brutal as you like) ways to improve the code or the algorithm (I'm aware there should be comments) - I'm a recreational programmer and would like to be improving my skills. My next step is to get the
targetNumber value from a nearby file without losing the current count.
Count to a particular target
Starting
currentValue = 100;
targetValue = 1500;
function count() {
if (currentValue > targetValue) {
currentValue -= 1
} else if (currentValue
Solution
function count(from, to, targetElem) {
targetElem.innerHTML = 'Total wordcount: ' + from;
if (from == to) return;
from < to ? from++ : from--;
var changeTime = Math.max(20, 1000 - Math.abs(from - to)) / 2;
setTimeout(function() {count(from, to, target);}, changeTime);
}
count(50, 0, document.getElementById("t"));A few notes:
- avoid global variables to conserve state - use function arguments instead
- always use
varto declare variables. Otherwise they are in the global scope and you don't want this
- added error checking (i.e. whether values are numeric and target is valid) might not be a bad idea, I left it out for clarity here
returnearly on known conditions, this reduces complexity in the function body
- the ternary operator
condition ? ifTrue : ifFalsecan be used in other ways than assigning a value
Code Snippets
function count(from, to, targetElem) {
targetElem.innerHTML = 'Total wordcount: ' + from;
if (from == to) return;
from < to ? from++ : from--;
var changeTime = Math.max(20, 1000 - Math.abs(from - to)) / 2;
setTimeout(function() {count(from, to, target);}, changeTime);
}
count(50, 0, document.getElementById("t"));Context
StackExchange Code Review Q#2669, answer score: 4
Revisions (0)
No revisions yet.