-2

How do I add a time interval to this code? I want the code to automatically fetch data during a specific time interval.

function fetch(){
  $.ajax({
    type: 'POST',
    url: 'resultsget.php',
    dataType: 'json',
    success: function(response){
      $('#content').html(response).iCheck({checkboxClass: 'icheckbox_flat-green',radioClass: 'iradio_flat-green'});
    }
  });
}
Sirh Eazi
  • 11
  • 1
  • Does this answer your question? [What's the easiest way to call a function every 5 seconds in jQuery?](https://stackoverflow.com/questions/2170923/whats-the-easiest-way-to-call-a-function-every-5-seconds-in-jquery) – Ivar Oct 24 '22 at 08:56
  • 1
    `fetch()` is a built-in method (of the global object `window`) that you're shadowing with your version. If you're the only one using this script/site you can do that - but even then it is a bad idea... – Andreas Oct 24 '22 at 09:00

2 Answers2

0

An easy solution is to recall your fetch function with a timeout inside the success function.

success: function (response) {
   $('#content').html( ... ) // elided
   setTimeout(fetch, 5000);  // <-- fetch again after (roughly) 5 seconds
}

Notes

You might want to rename your fetch function to something different, because as of now you are shadowing the build-in fetch function (see @Andreas comment).

You also might want to add a "stopping condition" inside the success callback that stops the polling mechanism from re-running.

David
  • 3,552
  • 1
  • 13
  • 24
0

In the following code:

wait returns a promise that is resolved after a specified number of milliseconds.

scheduled wraps a supplied callback function in a function that will delay the running of the callback until the supplied date (if the date has already passed it sets the delay to be zero).

fetchResults makes a test HTTP request.

const wait = (ms = 0) => 
    new Promise((resolve) =>
        setTimeout(resolve, ms))

const scheduled = (cb, when) => 
    async (...args) => {
        let interval = when - new Date
        interval = interval < 0 ? 0 : interval
        console.log('Waiting...')
        await wait(interval)
        return cb(...args)
    }

const fetchResults = () => {
    console.log('Sending HTTP request...')
    return fetch('https://eo45u4bbmp0xwqx.m.pipedream.net') // example URL
}

const scheduledFetchResults = scheduled(fetchResults, +new Date + 5000) // run five seconds from now

;(async function() {  
    console.log('Asking for results...')
    const results = await scheduledFetchResults()
    console.log('Results retrieved.')
    document.querySelector('code').innerHTML = await results.text()
})()
<code></code>
Ben Aston
  • 53,718
  • 65
  • 205
  • 331