簡體   English   中英

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的值,因此它是未定義的,因此它滿足並輸入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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM