简体   繁体   中英

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. 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 accomplish this using 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(() => 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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