1

I want to get data from the server every one second. Suppose that I have data.json in the server. I want to fetch that file. Can I use the following code.

function getData(){
    fetch('./data.json')
        .then((result) => console.log(result))
        .then(() => setTimeout(getData,1000))
        .catch((err) => console.log(err));
}

Does this method cause a stackoverflow. Cant I use fetch or do I need to use ajax. Is there a better way to implement this/

  • I edited it is it okay now – Lalani Gunathilaka Nov 27 '20 at 07:57
  • Does this method cause a stackoverflow since we are calling a method inside another – Lalani Gunathilaka Nov 27 '20 at 07:58
  • You need a way to handle the final response and cancel the timeout but this is the basic pattern yes. – Derek Nov 27 '20 at 07:58
  • No overflow caused here. The timer sends its arguments to a task queue, and the queue calls the callback function. In the meanwhile JS and browser are free to do other stuff. – Teemu Nov 27 '20 at 08:01
  • "*Does this method cause a stackoverflow since we are calling a method inside another*" [Why doesn't an infinitely recursive async function cause stack overflow?](https://stackoverflow.com/q/56205298) | [Javascript: settimeout recursion endless stack increase?](https://stackoverflow.com/q/54443801) – VLAZ Nov 27 '20 at 08:02

0 Answers0