Question | Click to View Answer |
Describe how the following code functions. setTimeout(function() {
console.log('greetings');
}, 1000);
|
This code waits 1000 milliseconds (1 second) and then prints 'greetings' to the console. The |
Describe how the following code functions. setInterval(function() {
console.log('boo!');
}, 500);
|
This code will print "boo!" to the console every 500 milliseconds (every half second). |
What does the following code print to the console? const smelly = setTimeout(function() {
console.log("throw stink bomb");
}, 1000);
clearTimeout(smelly);
|
The |
What does the following code print to the console? const hola = setInterval(function () {
console.log("hola!");
}, 500);
setTimeout(function () {
clearInterval(hola);
}, 2600);
|
This code prints "hola!" to the console five times. "hola" is printed at 500 milliseconds, 1000 milliseconds, 1500 milliseconds, 2000 milliseconds, and 2500 milliseconds. After 2600 milliseconds, the timer is cleared and "hola!" isn't printed anymore. |
What does the following code print to the console? setTimeout(function() {
console.log("before");
}, 1000);
setTimeout(function() {
console.log("middle");
}, 0);
console.log("after");
|
after
middle
before
The |
What does the following code print to the console? setTimeout(function() {
console.log("before");
}, 1000);
process.nextTick(function() {
console.log("middle");
});
console.log("after");
|
after
middle
before
The |
What does the following code print to the console? process.nextTick(function first_cool() {
console.log("snow day");
let counter = 0;
while(true) {
counter = counter + 1;
}
});
process.nextTick(function second_cool() {
console.log("rain day");
});
|
"snow day" is printed and nothing else is printed because the code gets stuck in an infinite loop. The Node event loop is single threaded and blocking. Subsequent events aren't executed until previous events are done running. Make sure you have a good command of how the Node event loop functions - it's an important concept to master. |