[英]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的值,因此它是未定义的,因此它满足并输入if语句。 现在,当try{}
调用该函数时,它将执行。 问题是我通过传递参数作为函数interval()
和ti
interval()
以毫秒为单位的时间interval()
调用SetInterval函数。
因此,它应该在时间ti
之后调用函数interval()
,但是没有这样做。
setTimeout
需要一个函数,您正在传递函数调用的值。
更改
setTimeout(interval(func,ti,f),ti);
至
setTimeout(() => interval(func,ti,f),ti);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.