javascript - 语法错误: Unexpected identifier in setInterval callback

标签 javascript

我正在尝试制作一个脚本,使用 selenium-webdriver 每 10 秒更新一次图像 src。

它在节点服务器上运行。 我无法理解为什么在编译时 javascript 在 setInterval 回调内的驱动程序变量上给出 “SyntaxError:意外标识符” 错误。

“deiver”变量不是在“example”函数的范围内,并且 setInterval 回调应该能够访问它吗?

const {Builder, By, Key, until} = require('selenium-webdriver');
var firefox = require('selenium-webdriver/firefox');
var FirefoxProfile = require('firefox-profile');

FirefoxProfile.copyFromUserProfile({name: 'foobar'}, function(err, profile) {
var opts = new firefox.Options();
opts.setProfile(profile.profileDir);
(async function example() {

    let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(opts).build();

    try {

        await driver.get('http://google.com');
        var myTimer = setInterval(()=>{
            var image = await driver.findElement(By.xpath("//img"));  // error is here
            var imageSrc = image.getAttribute('src');
        },1000*10);

    } catch(err) {
        console.log(err);
    } finally {
        await driver.quit();
    }

})();

});

错误:

/home/vikas/Development/node/webdriver/index.js:16
            var image = await driver.findElement(By.xpath("//img"));
                              ^^^^^^

SyntaxError: Unexpected identifier
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:537:28)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:598:3

最佳答案

由于您没有提供任何停止条件,您可以将 setInterval 替换为无限循环

// promisified "setTimeout" to use later
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))

(async function example() {

    let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(opts).build();

    try {

        await driver.get('http://google.com');

        while(true) { // run forever or use some condition to stop
           await delay(1000 * 10) // just wait 10 seconds

           var image = await driver.findElement(By.xpath("//img"));
           var imageSrc = image.getAttribute('src'); // do something useful, I guess
        }

    } catch(err) {
        console.log(err);
    } finally {
        await driver.quit();
    }

})();

关于javascript - 语法错误: Unexpected identifier in setInterval callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50296357/

相关文章:

javascript - 从字符串创建日期在浏览器中不同

javascript - 遍历具有对象的 json 对象

javascript - 主干没有用 require js 定义

javascript - 动态存储对 setTimeout() 的引用

javascript - 使用javascript测量多边形的圆度给出了错误的数字

javascript - D3JS - 组合 "rect"函数

javascript - 你怎么能在 highcharts 的图形和图例中表示超过 10 种颜色?

javascript - 如何阻止恶意机器人访问者的链接?

javascript - 发送查看......来自两个不同数据库的信息

php - ajax加载内容中的CSS