I am trying to implement simple polling mechanism using setInterval. I have a Viewmodel as follows:
define([ 'knockout', 'jquery',
], function ( ko, $) {
function ViewModel() {
var self = this;
//setInterval( function() {
$.ajax({url: "", async: false,timeout: 3000, success: function (data) {
// some operation
}, dataType: "json"});
//}, 3000);
}
return ViewModel;
});
Upto this it works fine ajax call return data and does operation.How do I use setInterval so that ajax call returns data after certain interval so that ViewModel is updated and data get refreshed in UI? If I uncomment the setInterval block then ViewModel is not getting returned to the DOM.I think setInterval is asynchronous. Any solutions is appreciated.
You could try simply doing:
The ajax call is made every
refreshInterval
(in ms). Thetimeout
property is a security to be sure the answer you get during one interval are the data of this interval, and not the data from a previously unanswered call that got late.Basically, using
setInterval
with async code is not the best way to go. It's better to usesetTimeout
to schedule a new request once the previous one has finished.If you make sure there can't be two pending requests at once, you can access your
ViewModel
instance throughself
in your success handler and you won't have to worry of older/other requests undoing your change.Here's an example: