Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to call the callback function after 1 second.
Javascript
function delayedAction(callback) {
setTimeout([1], 1000);
}
delayedAction(() => console.log('Done!')); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'callback()' inside setTimeout which calls the function immediately.
Forgetting to pass a function reference.
✗ Incorrect
The setTimeout function expects a function reference, so we pass 'callback' without parentheses to delay its execution.
2fill in blank
mediumComplete the code to print numbers 0 to 4 with a delay using callbacks.
Javascript
for (let i = 0; i < 5; i++) { setTimeout(() => { console.log([1]); }, i * 1000); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'var' instead of 'let' causing all callbacks to print 5.
Trying to access 'this.i' which is undefined in this context.
✗ Incorrect
Using 'let' in the loop creates a new binding for each iteration, so 'i' inside the callback has the correct value.
3fill in blank
hardFix the error in the callback to correctly handle asynchronous data.
Javascript
function fetchData(callback) {
setTimeout(() => {
const data = 'Hello';
[1](data);
}, 500);
}
fetchData((result) => {
console.log(result);
}); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Writing 'callback' without parentheses, so the function is not called.
Using 'callback.call' without calling it properly.
✗ Incorrect
We need to call the function 'callback' with the data as argument. Writing 'callback(data)' calls it correctly.
4fill in blank
hardFill both blanks to create a function that calls a callback only once after multiple async calls.
Javascript
function onceCallback(callback) {
let called = false;
return function() {
if (![1]) {
[2] = true;
callback();
}
};
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable name in the condition.
Not setting the flag to true after calling the callback.
✗ Incorrect
We use the 'called' variable to check if the callback was already called and set it to true after calling.
5fill in blank
hardFill all three blanks to fix the callback error and print numbers 0 to 4 with delay.
Javascript
for (var [1] = 0; [1] < 5; [1]++) { (function([2]) { setTimeout(() => { console.log([3]); }, [2] * 1000); })([1]); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same variable name inside and outside the IIFE causing confusion.
Not passing the loop variable to the IIFE.
✗ Incorrect
We use 'i' as the loop variable, 'j' as the parameter to the IIFE to capture the current value, and print 'j' inside the callback.