JavaScript 中我的自定义 setInterval() 函数出现问题
Problem in my custom setInterval() function in JavaScript
这里我做了一个自定义的 setInterval 函数,但它没有按预期工作。
function interval(func,ti,f){
if(f==0||f==undefined){
try{ //calls the function provided as argument.
func.call();
}
catch(err){ //if error occurs
alert('error occured!'); //edited
throw new Error("error occured!!");//edited
}
setTimeout(interval(func,ti,f),ti);
}
}
这背后的主要思想是用户调用函数有点像这样:
interval(()=>{
console.log('hello world');
},10000);
因为我没有传递 f 的值所以它是 undefined
所以它满足并进入if语句。现在,当 try{}
调用该函数时,它就会执行。问题是我通过将参数作为函数 interval()
和 ti
传递来调用 SetInterval 函数,这是以毫秒为单位的时间。
所以它应该在时间 ti
之后调用函数 interval()
但它没有这样做。
setTimeout
需要一个函数,你传递的是一个函数调用的值。
改变
setTimeout(interval(func,ti,f),ti);
到
setTimeout(() => interval(func,ti,f),ti);
这里我做了一个自定义的 setInterval 函数,但它没有按预期工作。
function interval(func,ti,f){
if(f==0||f==undefined){
try{ //calls the function provided as argument.
func.call();
}
catch(err){ //if error occurs
alert('error occured!'); //edited
throw new Error("error occured!!");//edited
}
setTimeout(interval(func,ti,f),ti);
}
}
这背后的主要思想是用户调用函数有点像这样:
interval(()=>{
console.log('hello world');
},10000);
因为我没有传递 f 的值所以它是 undefined
所以它满足并进入if语句。现在,当 try{}
调用该函数时,它就会执行。问题是我通过将参数作为函数 interval()
和 ti
传递来调用 SetInterval 函数,这是以毫秒为单位的时间。
所以它应该在时间 ti
之后调用函数 interval()
但它没有这样做。
setTimeout
需要一个函数,你传递的是一个函数调用的值。
改变
setTimeout(interval(func,ti,f),ti);
到
setTimeout(() => interval(func,ti,f),ti);