I'm so new to node.js I'm trying to make an interval value in node.js And I can invoke a function when I reach the exact URL, however, I do not know how to pass the console.log value to JSON value.
this is my code:
// Import packages
const express = require("express");
// App
const app = express();
const port = 8000;
app.get("/", (req, res) => {
function doSomething() {
console.log(Math.round(Math.random() * (3000 - 500)) 500);
}
const loop = () => {
setTimeout(() => {
doSomething();
loop();
}, 1000);
};
loop();
res.json({ random: doSomething() });
});
// Starting server
app.listen(port, () => console.log(`listening on port ${port}!`));
I'd like to pass the random number in doSomething function to
res.json` inside.
So, this is what I tried :
// Import packages
const express = require("express");
// App
const app = express();
const port = 8000;
let number;
app.get("/", (req, res) => {
function doSomething() {
number = Math.round(Math.random() * (3000 - 500)) 500;
return number;
}
const loop = () => {
setTimeout(() => {
doSomething();
loop();
}, 1000);
};
loop();
res.json({ random: doSomething() });
});
// Starting server
app.listen(port, () => console.log(`listening on port ${port}!`));
Thank you in advance
CodePudding user response:
I think it would be better to invoke your function from the client and using setInterval
instead of setTimeout
otherwise it only will run it once.
Keep your server code like this:
// Import packages
const express = require("express");
// App
const app = express();
const port = 8000;
let number;
app.get("/", (req, res) => {
function doSomething() {
number = Math.round(Math.random() * (3000 - 500)) 500;
return number;
}
res.json({ random: doSomething() });
});
// Starting server
app.listen(port, () => console.log(`listening on port ${port}!`));
Then, in a js loaded from the client (browser), you could do something like this:
setInterval(() => {
fetch("http://localhost:8000/")
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log("err", err))
}, 1000)
That said, using setInterval
may not be the best thing. I would recommend you to create a HTML <button>
or an <a>
and set up and event listener to handle the click event. Then, when the user clicks the button, you could invoke a function to execute the fetch operation.