Complete the code to schedule a function to run after 1000 milliseconds.
setTimeout(() => { console.log('Hello after 1 second'); }, [1]);The setTimeout function schedules the callback to run after the specified milliseconds. Here, 1000 means 1 second delay.
Complete the code to schedule a function to run repeatedly every 500 milliseconds.
const intervalId = setInterval(() => { console.log('Repeating every 0.5 seconds'); }, [1]);The setInterval function runs the callback repeatedly every given milliseconds. 500 means every half second.
Fix the error in the code to clear the interval after 3 seconds.
const id = setInterval(() => { console.log('Tick'); }, 1000);
setTimeout(() => { clearInterval([1]); }, 3000);The setInterval returns an ID which must be passed to clearInterval to stop it. Here, the ID is stored in id.
Fill both blanks to create a Promise that resolves after 2 seconds using setTimeout.
const delay = ms => new Promise(resolve => {
setTimeout(() => {
[1]();
}, [2]);
});Inside the Promise, resolve is called to mark it as done. The delay time is passed as milliseconds to setTimeout.
Fill all three blanks to create a map of words to their lengths, but only for words longer than 3 characters.
const words = ['apple', 'bat', 'carrot', 'dog']; const lengths = words.reduce((acc, [3]) => { if ([3].length > 3) { acc[[1]] = [2]; } return acc; }, {});
The reduce method creates an object that maps each word to its length word.length for words longer than 3 characters.