UNB/ CS/ David Bremner/ teaching/ cs2613/ labs/ Lab 13

Before the Lab

Background


Review

Time
10 minutes

Timers

Time
20 minutes
Activity
Demo, group discussion

In this section we look at some of the simplest examples of asynchronous programming in JavaScript. This means that rather than running functions directly, we let the runtime invoke them later triggered by some event.

In order to have some crude simulation of animation, we want to clear the terminal screen between printing slightly different pictures. It turns out that for most terminals, it suffices to print out the ANSI escape "ESC c" to reset the terminal.

Our first attempt at animation is

let str="";
for (let i=0; i<60; i++) {
    console.log('\033c');
    str+= "*";
    console.log(str);
}

console.log("all done!");

Something is not quite as desired here; in particular if we move the console.log outside the loop, the visual effect is the same. The obvious answer is to delay between iterations. Unlike some programming languages, JavaScript does not define a sleep builtin to pause the current thread. This is mainly because there is only one thread in JavaScript (including node.js). Instead there is built-in support for timers. Perhaps the simplest (or at least the shortest) way to get what we want is to use setTimeout like the following example:

function loop(i,str) {
    if (i>0) {
        console.log("\033c");
        console.log(str);
        setTimeout(function() { loop(i-1, str+"*"); }, 1000);
    }
}

loop(20,"*");

console.log("all done!");

Something is not quite right here either with the printing of "all done!". Let's trace out a smaller example like loop(3,"*") by hand to try and understand what's going on.

Timers part II

Time
20 minutes
Activity
Individual

If you don't like the recursive style of the previous example, you can use setInterval, but you have to explicitly cancel timer with clearInterval timer, or it runs forever. Fill in the blanks in the following animation.

function animate(iterations) {
    let i=0;
    let str="";
    let timer = null;
    function frame() {
        // add code here
        console.log('\033c');
        console.log(str);
        if (i>=iterations)
            // and here
    }
    timer=setInterval(frame,300);
}

animate(20);

JavaScript Quiz