将Java等待函数转为JS后无法获取更新毫秒数,求排查问题
问题排查:JS等待函数时间差值不更新的问题
问题描述
我是JavaScript新手,尝试将下方的Java等待函数转换为JS代码,该函数的作用是等待指定值变为非空。但转换后无法获取更新的当前毫秒数,即使在循环内重新赋值,时间差值也不会随检查间隔变化,功能未达预期。
当前结果 -> 时间差值不会随指定检查间隔变化
我的JS代码
waitUntilValueComes(value, timeout, checkInterval) { let currentTime = new Date().getMilliseconds() cy.log('Current time ' + currentTime) let diff = new Date().getMilliseconds()- currentTime while (timeout > (diff)) { cy.log('Date time ' + diff) if (value != null) { break } cy.wait(checkInterval) diff = new Date().getMilliseconds()- currentTime } }
参考Java代码
public void waitUntilValueComes(String value, long timeout, long checkInterval) throws InterruptedException { long currentTime = System.currentTimeMillis(); while (timeout > System.currentTimeMillis() - currentTime) { if (value!= null) break; LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(checkInterval)); } }
问题根源
时间获取逻辑错误
Java的System.currentTimeMillis()返回从1970年至今的总毫秒数(时间戳),但你在JS里用了new Date().getMilliseconds(),这个方法只返回当前时间的毫秒部分(0-999),比如当前时间是10:00:00.123,它返回123;过1秒后是10:00:01.456,返回456,计算出的差值完全不是实际流逝的时间,自然不会随等待间隔变化。Cypress异步模型冲突
cy.wait()是Cypress的异步命令,同步while循环不会等待它执行完成,会瞬间跑完所有循环迭代,根本不会按你设置的checkInterval等待。Cypress的所有API都是异步的,不能用同步循环来控制流程。值的检查逻辑无效
直接传value参数只会获取一次初始值,即使后续值发生变化,循环里的value还是最初的null,无法检测到更新。
修复后的代码
waitUntilValueComes(valueGetter, timeout, checkInterval) { const startTime = Date.now(); // 获取正确的时间戳(从1970年至今的毫秒数) const checkValue = () => { // 每次检查时通过函数获取最新值 const currentValue = valueGetter(); if (currentValue != null) { return; // 值已就绪,终止检查 } const elapsedTime = Date.now() - startTime; if (elapsedTime >= timeout) { throw new Error(`等待超时,超时时间:${timeout}ms`); } // 异步等待后递归检查,符合Cypress执行模型 cy.wait(checkInterval).then(checkValue); }; checkValue(); }
修复说明
- 用
Date.now()替代getMilliseconds():获取正确的时间戳,确保时间差计算准确。 - 改用
valueGetter函数传参:每次检查时重新获取最新值,避免初始值的快照问题。 - 递归+异步等待:用
cy.wait().then()替代同步循环,适配Cypress的异步执行逻辑,确保等待完成后再检查值和时间。
使用示例
比如等待某个元素的文本非空:
this.waitUntilValueComes( () => cy.get('.target-element').invoke('text').then(text => text.trim()), 5000, // 超时时间5秒 500 // 每500毫秒检查一次 );
内容的提问来源于stack exchange,提问作者sebilet
相关产品推荐
相关产品推荐

