Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 调用另一个回调函数的setInterval回调无效_Javascript_Setinterval - Fatal编程技术网

Javascript 调用另一个回调函数的setInterval回调无效

Javascript 调用另一个回调函数的setInterval回调无效,javascript,setinterval,Javascript,Setinterval,这是我的密码 function doIt(context, startTime) { context.url((currentURL) => { console.log("URL: " + currentURL.value) }) console.log("running timer function ") if (new Date() - startTime > 5000) { // timeo

这是我的密码

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秒),而是只运行一次,输出结果为

running timer function
keep on truckin'
URL: https://michigan.magellanrx.com/
如果我注释掉前3行代码(context.url函数),那么代码将按预期运行,并输出

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函数没有被注释掉时,代码没有在所有五次迭代中运行


对此的澄清。。。结果证明它不会只运行一次。实际上,当包含前3行代码时,setInterval函数正在从“阻塞”函数变为“非阻塞”函数。因此,它不是在继续之前运行所有五次迭代,而是只运行第一次迭代,然后继续执行后续命令,而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
只生成一次输出。

上下文.url()
做什么?它是否执行重定向?如果执行重定向,将取消此页面上运行的JavaScript。上下文.url()检索当前url。'“上下文”是一个浏览器实例。发布代码时,其中有干扰。