Home > Enterprise >  How do I add a time interval to this code?
How do I add a time interval to this code?

Time:10-24

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'});
    }
  });
}

CodePudding user response:

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.

CodePudding user response:

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 = () =>
    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>

  • Related