Javascript:回调不是一个函数
roll()函数工作得很好,但当我尝试获取回调时,它会抛出错误:回调不是函数Javascript:回调不是一个函数,javascript,Javascript,roll()函数工作得很好,但当我尝试获取回调时,它会抛出错误:回调不是函数 var speed = 300; function roll(callback) { if (typeof callback === "function") { console.log('callback is function!'); //yes } if (speed < 1000) { speed += 50; setTimeout(roll, 1000); //incr
var speed = 300;
function roll(callback) {
if (typeof callback === "function") {
console.log('callback is function!'); //yes
}
if (speed < 1000) {
speed += 50;
setTimeout(roll, 1000); //increase speed
} else if (speed >= 1000) {
console.log('finished');
return callback(true); //problem here?
}
}
roll(function(callback) {
console.log(callback); //callback is not a function
});
var速度=300;
函数滚动(回调){
if(回调类型==“函数”){
console.log('callback is function!');//是
}
如果(速度<1000){
速度+=50;
setTimeout(滚动,1000);//增加速度
}否则,如果(速度>=1000){
console.log('finished');
返回回调(true);//这里有问题吗?
}
}
滚动(函数(回调){
console.log(回调);//回调不是函数
});
问题的根本原因是:设置超时(滚动,1000)
roll
正在被调用,但是设置超时
没有调用回调
函数
var速度=300;
函数滚动(回调){
log('callback',callback);
如果(速度<1000){
速度+=50;
setTimeout(函数(){
滚动(回调);//传递回调
},1000);//提高速度
}否则{
console.log('finished');
回调(true);//已删除不需要的`return`
}
}
roll(函数(结果){//重命名参数
控制台日志(结果);
});代码>问题的根本原因是:设置超时(滚动,1000)
roll
正在被调用,但是设置超时
没有调用回调
函数
var速度=300;
函数滚动(回调){
log('callback',callback);
如果(速度<1000){
速度+=50;
setTimeout(函数(){
滚动(回调);//传递回调
},1000);//提高速度
}否则{
console.log('finished');
回调(true);//已删除不需要的`return`
}
}
roll(函数(结果){//重命名参数
控制台日志(结果);
});代码>当这部分代码触发时,roll
未被赋予回调
参数:
setTimeout(roll, 1000); //increase speed
因此,当执行这部分代码时:
return callback(true); //problem here?
// ^^^^^^^^^^^^^^
回调
是未定义的
,因此不是函数
。通过执行以下操作可以避免出现此错误:
else if (speed >= 1000) {
console.log('finished');
if(typeof callback === 'function'){
return callback(true);
}else{
// do what you want here if callback is undefined
}
}
当这部分代码触发时,roll
未被赋予回调
参数:
setTimeout(roll, 1000); //increase speed
因此,当执行这部分代码时:
return callback(true); //problem here?
// ^^^^^^^^^^^^^^
回调
是未定义的
,因此不是函数
。通过执行以下操作可以避免出现此错误:
else if (speed >= 1000) {
console.log('finished');
if(typeof callback === 'function'){
return callback(true);
}else{
// do what you want here if callback is undefined
}
}