简体   繁体   中英

setInterval() in EJS template does not work

I'm currently stuck with a problem in a homework project. I'm trying to make a project where the price of bitcoin will update every second. Now the API request is working fine and I can see the data render from an EJS template but I can't make the price update every second. Can anyone check my code and see if anything is wrong in my code? For reference please check www.preev.com. It shows how I want the price to be updated. And also check below my code.

I have tried to call the API request in app.js file and rendered it in an EJS template called results.ejs.

app.js

var express = require("express");
var app = express();
var request = require("request");


app.set("view engine", "ejs");


app.get("/", function(req, res) {
    request("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true&include_last_updated_at=true", function(error, response, body) {
        if(!error && response.statusCode == 200) {
            var data = JSON.parse(body);
            res.render("result", {data: data});
        }
    });
});




app.listen(3000, function(){
    console.log("server has started");
});


results.ejs

<h1>
    Bitcoin Latest
</h1>



Price: $ <span id="showPrice"></span> 
<br>
MarketCap: $<%= data["bitcoin"]["usd_market_cap"] %>
<br>
24h Volume: $<%= data["bitcoin"]["usd_24h_vol"] %>
<br>
24h Change: <%= data["bitcoin"]["usd_24h_change"] %>%


<script>
    function updatePrice(){
        document.getElementById("showPrice").innerHTML= <%= data["bitcoin"]["usd"] %>;
    };

    setInterval(updatePrice, 500);
</script>

Initial answer

Your setInterval works fine, it's just that inside your function the data never changes.

To fix it you have to reference a variable (of which the content changes), rather than hardcoding the value in your function.

Extra explanation

For example you are using EJS, which is a templating language . A templating language parses output based on your variables (once per page load).

Your template line

document.getElementById("showPrice").innerHTML= <%= data["bitcoin"]["usd"] %>;

parses into

document.getElementById("showPrice").innerHTML= 9624.46;

And your interval then updates the innerHTML of #showPrice with that value, every 500 ms.

What you probably mean to do is make the request from the client (the browser), then store its response into a variable, say latestResult , and then code your function to reference that variable, like so:

document.getElementById("showPrice").innerHTML= latestResult;

Example implementation

This means that your express application (app.js) will render result without data:

app.get('/', function(req, res) {
  res.render('result');
});

And the request part will be in your template:

function updateLatestPrice() {
  fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true&include_last_updated_at=true').then((result) => {
    const latestResult = result.bitcoin.usd

    document.getElementById("showPrice").innerHTML = latestResult || 'failed'
  })
}

setInterval(updateLatestPrice, 3000)

Note that I changed request into fetch here because I couldn't be sure whether your client code has babel, so I went with the browser's native Fetch API .

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