繁体   English   中英

调用另一个回调 function 的 setInterval 回调不起作用

[英]setInterval callback that calls another callback function is not working

这是我的代码

function doIt(context, startTime) {
    context.url((currentURL) => {
        console.log("URL: " + currentURL.value)
    })
    console.log("running timer function ")
    if (new Date() - startTime > 5000) { // timeout = 5 seconds
        console.log("timed out")
        clearInterval(timerId) // exit the loop
    } else {
        console.log("keep on truckin'")
    }
}

let timerId = setInterval(doIt, 1000, this, Date.now())

它不是循环五次(每秒一次,持续 5 秒),而是只运行一次,结果 output 显示为...

running timer function
keep on truckin'
URL: https://michigan.magellanrx.com/

如果我注释掉前 3 行代码(context.url 函数),那么代码将按预期运行 output...

running timer function
keep on truckin'
running timer function
keep on truckin'
running timer function
keep on truckin'
running timer function
keep on truckin'
running timer function
timed out

当 context.url function 没有被注释掉时,为什么代码没有运行所有五次迭代?

对此进行澄清......事实证明它不只运行一次。 实际上,当包含前 3 行代码时,setInterval function 正在从“阻塞”function 变为“非阻塞”function。 因此,它不会在继续之前运行所有五次迭代,而是仅运行第一次迭代然后继续执行后续命令,同时 setInterval 继续在后台运行。

根据您对症状的描述,听起来您可能在context.url()中有一个无限循环

无限循环阻塞主线程,从而导致没有事件被处理。 您需要找到并删除那个无限循环。


javascript在C/C++中是如何实现的

javascript 解释器的实现方式通常如下所示:

// pseudocode:
do {
    eventHandlers = executeJavascript();
    // end of execution

    events = waitForAllIO(); // this actually blocks but it is waiting
                             // for ALL I/O instead of just one

    if (events.timeout) {
        foreach (callback from eventHandlers) {
            if (callback is TIMEOUT_HANDLER) {
                callback(events.timeout);
            }
        }
    }
    else {
        foreach (event from events) {
             foreach (callback from eventHandlers) {
                 if (callback is for event) {
                     callback(event);
                 }
             }
        }
    }
} while (eventHandlers.length > 0)

如果您的代码正在执行无限循环,则意味着解释器会卡在executeJavascript()部分。 这意味着没有定时器或网络数据包或任何其他事件得到处理。 这解释了为什么您的setInterval只产生一次 output 。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM