0

I want to apply max timeout to one fucntion so task is not done in given time, it just notify the calling fuction it just move to next step.

what is best way to do it in pure Javascript.(ES5) here is Samelto explain my query.



function dowatch() {
  var cnt = 0;
    //function to keep checking (max timeout )if in given time,result is achieved or not and move to next steps
//should setTimeout of max time can be used instead of regular check?
    var hnd = setInterval(function() {
        cnt += 1;
        //max try is 5 times on 250ms regular interval to check window.cdoneis defined or not
        if (cnt >= 5 || (window.cdone)) {
            clearInterval(hnd);
            // call function anyway
            notifyTotohers();
        }
    }, 250);
}

function getDataFrmExtSource(cb) {
    //here call ajax call  & read response or inject iframe and read data from it
    //...

    //once done ,callback or raise window.customEvent()
    typeof cb == 'function' && cb();
}

//call back function
function taskdone() {
    window.cdone = true;//this will cancel the setinerval
    notifyTotohers();
}

function notifyTotohers() {
    //method continue other task called only once
if(!window.notified){window.notified=true;
//calltoher fucntion
}

}

//main function
try {
    //get data from ifram or ajax -external source
    getDataFrmExtSource(taskdone);

} catch (ex) {} finally {
//start timer to keep checking on regular interval till max time reached.
    dowatch();
}
  • Are you saying that you want to cancel an XHR (ajax) request if it's not complete within a given time allotment? –  Jun 16 '20 at 21:27
  • @slappy , thx for reply. I do not want to cancel ext. task but I want to continue with other method if i do not get result in X second. – user3796012 Jun 16 '20 at 21:31
  • If you have access to the request object, I would use a `setTimeout` for whatever duration you want, and have it look at the request object to see its status. If the request is not complete, you can invoke your other function. –  Jun 16 '20 at 21:33
  • Have a look at [doing it with promises](https://stackoverflow.com/q/37120240/1048572) – Bergi Jun 16 '20 at 21:44
  • @Bergi, I can not use promise currently on this app. – user3796012 Jun 18 '20 at 03:30

0 Answers0