JavaScript: sequencing function calls