最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError thrown by setInterval using node.js's - Stack Overflow

programmeradmin2浏览0评论

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. I am attempting to use the package 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(...).

Any idea how I acplish this using setInterval?

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. I am attempting to use the package 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(...).

Any idea how I acplish this using setInterval?

Share Improve this question edited Jun 27, 2018 at 21:46 Bee 1,3062 gold badges10 silver badges24 bronze badges asked Jun 27, 2018 at 16:13 Daniel Daniel 1691 gold badge4 silver badges10 bronze badges 3
  • Where are you getting the error? I assume inside of the openUpPage function? – Luca Kiebel Commented Jun 27, 2018 at 16:15
  • 1 You are executing openUpPage("myURl") and setting what it returns to setInterval. Since it does not return anything your call is basically. setInterval(undefined, 20000); Not related to the problem, but your code will not run on an interval. – epascarello Commented Jun 27, 2018 at 16:25
  • 1 @Luca The open implementation within the openurl package states that the callback is optional. So I assumed the error occurs at setInverval. – Bee Commented Jun 27, 2018 at 16:25
Add a ment  | 

1 Answer 1

Reset to default 8

You need to pass a callback to setInterval instead of calling your function right away using an anonymous arrow function as an example.

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. The code snippet from the question runs without any errors within codepen (using 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. Therefore browsers and node.js not necessarily share the same implementation as seen in the docs.

  • Node implementation
  • Common browser implementation

Even though calling the function right away as seen in the questions snippet is pointless in bination with setInterval no matter the implementation.

发布评论

评论列表(0)

  1. 暂无评论