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/

5
  • I edited it is it okay now Commented Nov 27, 2020 at 7:57
  • Does this method cause a stackoverflow since we are calling a method inside another Commented Nov 27, 2020 at 7:58
  • You need a way to handle the final response and cancel the timeout but this is the basic pattern yes. Commented Nov 27, 2020 at 7: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. Commented Nov 27, 2020 at 8: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? | Javascript: settimeout recursion endless stack increase? Commented Nov 27, 2020 at 8:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.