在淘汰应用程序中使用setInterval轮询实现? [英] Polling implementation using setInterval in knockout application?

查看:107
本文介绍了在淘汰应用程序中使用setInterval轮询实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用setInterval实现简单的轮询机制.我有一个Viewmodel如下:

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;


 });

到目前为止,它可以很好地运行ajax调用返回数据并执行操作.如何使用setInterval以便ajax调用在一定间隔后返回数据,以便在用户界面中更新ViewModel和刷新数据?如果我取消注释setInterval块,则ViewModel不会返回到DOM.我认为setInterval是异步的.任何解决方案都值得赞赏.

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.

推荐答案

基本上,将setInterval与异步代码一起使用并不是最好的方法.最好在上一个请求完成后使用setTimeout安排新请求.

Basically, using setInterval with async code is not the best way to go. It's better to use setTimeout to schedule a new request once the previous one has finished.

如果确保一次没有两个未决请求,则可以在成功处理程序中通过self访问ViewModel实例,而不必担心较旧/其他请求会撤消更改

If you make sure there can't be two pending requests at once, you can access your ViewModel instance through self in your success handler and you won't have to worry of older/other requests undoing your change.

这是一个例子:

function ViewModel() {
  var self = this;

  var INTERVAL = 5000;
  var timeout = null;
  var currentReq = null;
  
  this.observableProp = ko.observable("empty");

  var fetchNewData = function() {
    currentReq = $.ajax( /* options */);
    
    currentReq
      .done(processNewData)
      .always(scheduleNewDataFetch);
  };

  var processNewData = function(data) {
    // self refers to your current ViewModel instance
    // set observable properties using self.prop(data)
    self.observableProp("data");
  };
  
  var scheduleNewDataFetch = function() {
    if (currentReq) {
      currentReq.abort();  
    }
    
    if (timeout) {
      clearTimeout(timeout);  
    }
    
    currentReq = null;
    timeout = setTimeout(fetchNewData, INTERVAL);
    
  };

  fetchNewData(); // Starts the update loop
}

这篇关于在淘汰应用程序中使用setInterval轮询实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆