0

I want to update stock prices on my page every minute and display new prices without refreshing the page. Could you please help me how to do this.

 $(function () {
    var stocks = [];
    var symbols = ['AAPL', 'MSFT'];

    symbols.forEach(symbol => makeAjaxCall(symbol));

    function makeAjaxCall(param) {
        $.ajax({
            type: "GET",
            url: "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=" + param + "&interval=1min&apikey=8TKKZE0GET944FMW",
            success: function (result) {
                stocks = result;
                getPrices();
            }
        });
    }

    function getPrices() {
        var metaData = stocks["Meta Data"],
            timeSeries = stocks["Time Series (1min)"],
            symbol = metaData["2. Symbol"];
        var priceList2 = '';
        Object.getOwnPropertyNames(lastDate).forEach(function (val, idx, array) {
            priceList += val + ': ' + lastDate[val] + '<br>';
        });

        document.getElementById("demo").innerHTML += '<div class="eachStock"><a href="#" data-stock="' + symbol + '">' + symbol + '</a></div><div>' + priceList + '</div>';
    }
});

My html file:

<div id="demo"></div>

Thanks!

Luan Nico
  • 5,376
  • 2
  • 30
  • 60
Olga
  • 69
  • 1
  • 8
  • Possible duplicate of [JavaScript: get code to run every minute](https://stackoverflow.com/questions/13304471/javascript-get-code-to-run-every-minute) –  Dec 22 '17 at 16:54
  • [setInterval\(\)](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) – 001 Dec 22 '17 at 16:55

1 Answers1

1

First wrap all your code in a function call:

const loadData = () => {
    var stocks = [];
    var symbols = ['AAPL', 'MSFT'];

    symbols.forEach(symbol => makeAjaxCall(symbol));

    function makeAjaxCall(param) {
        $.ajax({
            type: "GET",
            url: "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=" + param + "&interval=1min&apikey=8TKKZE0GET944FMW",
            success: function (result) {
                stocks = result;
                getPrices();
            }
        });
    }

    function getPrices() {
        var metaData = stocks["Meta Data"],
            timeSeries = stocks["Time Series (1min)"],
            symbol = metaData["2. Symbol"];
        var priceList2 = '';
        Object.getOwnPropertyNames(lastDate).forEach(function (val, idx, array) {
            priceList += val + ': ' + lastDate[val] + '<br>';
        });

        document.getElementById("demo").innerHTML += '<div class="eachStock"><a href="#" data-stock="' + symbol + '">' + symbol + '</a></div><div>' + priceList + '</div>';
    }
};

You need to make sure it can be called many times, in which it mustn't append values, but replace (just clear the div at the begining, like document.getElementById("demo").innerHTML = ''). Then, you can use setInterval to call your function every so often. Don't forget to start it only when the page is loaded (you were using jquery for that, there are other options):

const TIME = 2 * 1000; // time in millis for next update
$(() => {
    loadData();
    setInterval(loadData, TIME);
});

Note that if the request takes more time than TIME, you might get concurrency issues. For a better solution, take a look at Promises. They'll allow for a cleaner code.

If you are using jquery just for request making and the 'has page loaded' event, you might want to learn newer alternatives (like the Fetch API and this event).

Luan Nico
  • 5,376
  • 2
  • 30
  • 60