简体   繁体   English

setInterval使用node.js抛出的TypeError

[英]TypeError thrown by setInterval using node.js's

I am new to NodeJS, I have a microservice running which I want to open a webpage without a browser, to make client side api requests every 20 seconds. 我是NodeJS的新手,我正在运行一个微服务,我想在没有浏览器的情况下打开网页,以每20秒发出一次客户端api请求。 I am attempting to use the package openurl 我正在尝试使用包openurl

const openPage = require("openurl");

function openUpPage(url){
  openPage.open(url);
}

setInterval(openUpPage("myURl"), 20000);

However I am being returned "TypeError: "callback" argument must be a function" when calling setInterval(...) . 但是,在调用setInterval(...)时,返回“ TypeError:“ callback”参数必须是一个函数“。

Any idea how I accomplish this using setInterval? 知道我如何使用setInterval完成此操作吗?

You need to pass a callback to setInterval instead of calling your function right away using an anonymous arrow function as an example. 您需要将回调传递给setInterval而不是使用匿名箭头函数作为示例立即调用函数。

setInterval(() => openUpPage("myURl"), 20000);

The arrow function isn't a must have though. 箭头功能不是必须的。

setInterval(function() { openUpPage("myURl") }, 20000);

When testing I figured out the error "TypeError: "callback" argument must be a function" thrown by setInverval is related to node.js. 测试时,我发现setInverval抛出的错误"TypeError: "callback" argument must be a function"与node.js有关。 The code snippet from the question runs without any errors within codepen (using Chrome). 问题中的代码段运行时在Codepen中没有任何错误(使用Chrome)。

This is caused because of the fact that pure javascript can't implement such timer-related functions due to the lack of low level support. 这是由于以下事实造成的:由于缺少底层支持,纯JavaScript无法实现此类与计时器相关的功能。 Therefore browsers and node.js not necessarily share the same implementation as seen in the docs. 因此,浏览器和node.js不一定共享文档中所见的相同实现。

Even though calling the function right away as seen in the questions snippet is pointless in combination with setInterval no matter the implementation. 即使如代码片段所示立即调用函数,与setInterval结合使用,无论实现如何,都是毫无意义的。

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

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