0

please note this is in code.org, so code is slightly different, but it's still javascript. I keep getting this message from this portion of code, and don't quite understand.

var ii = 0;
  while (ii < 4) { 
  setTimeout(callback(ii), 1000);
  ii++;
}

});
function callback(t) { 
  playSound(("key0"+(allnotelist[t]+1))+".mp3",false); 
}

Message in question: setTimeout() callback parameter value (undefined) is not a function

2 Answers2

1

pass a function not a return of its
change setTimeout(callback(ii), 1000); to setTimeout(() => callback(ii), 1000);

Hao.Le
  • 183
  • 10
  • Hello, I tried replacing it so it reads like ```onEvent("noteplayer", "click", function( ) { var ii = 0; while (ii < 4) { setTimeout(() => callback(ii), 1000); ii++; } }); function callback(t) { playSound(("key0"+(allnotelist[t]+1))+".mp3",false); }``` now, and it doesnt work as intended, did i do something incorrect? – Michael Lutz Aug 18 '22 at 05:16
  • I don't see this to add anything to davidhu's answer. – greybeard Aug 21 '22 at 13:44
  • You want to play each song after 1s, right? try this. ``` lang-js sequencePlay = (cb, max) => { let counter = 0; const id = setInterval(() => { if(counter < max){ cb(counter); counter++; } else { clearInterval(id) } }, 1000) } sequencePlay((i) => { console.log(i) }, 4) ``` – Hao.Le Aug 22 '22 at 02:31
0

The issue is how you're passing the handler to setTimeout

when you do

setTimeout(callback(ii), 1000);

what you're doing is basically

setTimeout(/* returned value of callback */, 1000);

which by looking at the callback function definition, it returns undefined since you don't explicitly return anything. So you're doing

setTimeout(undefined, 1000)

The way to fix the error is by creating a new function

setTimeout(() => callback(ii), 1000)
davidhu
  • 9,523
  • 6
  • 32
  • 53