0
0
Javascriptprogramming~10 mins

Callback pitfalls in Javascript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Acallback()
Bcallback
Ccallback.call()
Dcallback.apply()
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'callback()' inside setTimeout which calls the function immediately.
Forgetting to pass a function reference.
2fill in blank
medium

Complete 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'
Awindow.i
Bvar i
Cthis.i
Di
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.
3fill in blank
hard

Fix 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'
Acallback.call
Bcall
Ccallback()
Dcallback
Attempts:
3 left
💡 Hint
Common Mistakes
Writing 'callback' without parentheses, so the function is not called.
Using 'callback.call' without calling it properly.
4fill in blank
hard

Fill 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'
Acalled
Bcallback
Ctrue
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable name in the condition.
Not setting the flag to true after calling the callback.
5fill in blank
hard

Fill 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'
Ai
Bj
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.