Sequencing function calls in JavaScript