setTimeout 提前调用函数

如何解决setTimeout 提前调用函数

我的库有基于实时的测试用例,我注意到测试会随机失败,错误为 1 毫秒:

expect(received).toBeGreaterThanOrEqual(expected)

    Expected: >= 1000
    Received:    999

这似乎是由于 setTimeout 过早地调用了该函数。

所以我写了一个单独的测试脚本:

let last = Date.now()

setTimeout(next,1000)

function next() {
  if (Date.now() - last < 1000) process.exit(1)
  last = Date.now()
  setTimeout(next,1000)
}

在Node.js v12.19.0、v14.15.3、v15.4.0上,会随机失败:有时脚本可以继续运行,有时脚本很快就会退出。 这不仅发生在我的本地计算机上,而且发生在 Github 的 CI 服务器上。

我的问题:这是一个错误吗?或者 setTimeout 的某种预期行为?还是 Date.now() - time 总是需要加 1 毫秒?

更新:另见https://github.com/nodejs/node/issues/26578

解决方法

更新:此处使用 def Trapezoidal(f,a,b,n): h = (b-a)/float(n) s = 0.5*(f(a) + f(b)) for i in range(1,n,1): s = s + f(a + i*h) return h*s def g(t): return (1/(0.003172*0.001*(3.3-t))) a = 0; b = 3.3 n = 20 result = Trapezoidal(g,n) print (result) 是罪魁祸首:

git-bisect

这似乎是一个错误,而不是预期的行为。我会投票反对总是添加 1ms,因为行为不一致。 (但是,它会早于 1 毫秒吗?我没有观察到超过 1 毫秒)您可以通过以下方式解决该问题:

2c409a285359faae58227da283a4c7e5cd9a2f0c is the first bad commit
commit 2c409a285359faae58227da283a4c7e5cd9a2f0c
Date:   Tue Aug 25 13:36:37 2020 -0600

    perf_hooks: add idleTime and event loop util
    
    Use uv_metrics_idle_time() to return a high resolution millisecond timer
    of the amount of time the event loop has been idle since it was
    initialized.
    
    Include performance.eventLoopUtilization() API to handle the math of
    calculating the idle and active times. This has been added to prevent
    accidental miscalculations of the event loop utilization. Such as not
    taking into consideration offsetting nodeTiming.loopStart or timing
    differences when being called from a Worker thread.
    
    PR-URL: https://github.com/nodejs/node/pull/34938

即使在解决问题的同时,它也允许const origSetTimeout = setTimeout; setTimeout = (f,ms,...args) => { let o; const when = Date.now() + ms,check = ()=> { let t = when - Date.now(); if (t > 0) Object.assign(o,origSetTimeout(check,t)); else f(...args); }; return o = origSetTimeout(check,ms); };

这是一个模拟问题并每 3 秒更换一次解决方法的浏览器代码:

clearTimeout()

下面是一个 nodejs 代码,它会清楚地显示问题(点中的“p”),并在按 Enter 后应用解决方法。

// Simulate the problem
const realOrigSetTimeout = setTimeout;
setTimeout = (func,...args) => realOrigSetTimeout(func,ms - Math.random(),...args);

const ms = 200;
let when = Date.now() + ms;
setTimeout(next,ms);

function next() {
  let now = Date.now();
  setTimeout(next,ms);
  console.log(now < when ? 'premature' : 'ok');
  when = now + ms;
}

function workAround() {
  console.log('Applying workaround');

  const origSetTimeout = setTimeout;
  setTimeout = (f,...args) => {
    let o;
    const when = Date.now() + ms,check = ()=> {
        let t = when - Date.now();
        if (t > 0) Object.assign(o,t));
        else f(...args);
      };
    return o = origSetTimeout(check,ms);
  };

  setTimeout(_=>{
    console.log('Removing workaround');
    setTimeout = origSetTimeout;
    setTimeout(workAround,3000);
  },3000);
}
setTimeout(workAround,3000);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-