使用setInterval无效的javascript自动刷新

时间:2017-12-07 17:22:33

标签: javascript jquery knockout.js setinterval

我有一些sharepoint使用的自定义javascript代码。我需要在加载后自动刷新页面的一部分。我尝试过使用setInterval。这是我的职能:

define([
  'jquery',
  'knockout',
  'text!./home-page-census.html',
  'q',
  'underscore',
  'census',
  'moment',
  'sp_core',
  'bootstrap',
  '!domReady'
], function ($, ko, htmlString, Q, _, census, moment) {
    var baseUrl = _spPageContextInfo.siteAbsoluteUrl;

    function buildRequestUrl() {
        var requestUrl = baseUrl + "/_api/web/lists/GetByTitle('Census')/items?";
        var oDataSelect = "$select=Title,CensusBranch,BedAvailabilityPercentage,Modified,StatusBarColor,DisplayText,Tooltip";

        return requestUrl += oDataSelect;
    }

    function getUpdatedCensus() {
        return Q.Promise(function (resolve, reject, notify) {
            requestUrl = buildRequestUrl();
            census.getCensus(requestUrl).then(onFulfilled, onRejected);
            //setInterval(census.getCensus(requestUrl).then(onFulfilled, onRejected), 3000);

            function onFulfilled(censusResult) {
                resolve(censusResult);
            }

            function onRejected(reason) {
                reject(reason);
            }
        });
    }

    function initViewModel(viewModel) {
        getUpdatedCensus().then(onFulfilled, onRejected);

        function onFulfilled(result) {
            viewModel.censusByBranch(result);
            viewModel.isInitializing(false);
        }

        function onRejected(reason) {
            console.log(reason.message);
            console.log(reason.stack);
            viewModel.isInitializing(false);
        }
    }

    function HomePageCensusViewModel(params) {
        var self = this;
        self.isInitializing = ko.observable(true);
        self.censusByBranch = ko.observable();

        initViewModel(self);
    }

    ko.bindingHandlers.censusLastUpdatedTime = {
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var value = valueAccessor();
            var lastUpdated = ko.unwrap(value);

            $(element).text(lastUpdated.format('M[/]DD [@] h[:]mmA'));
        }
    }

    return {
        viewModel: HomePageCensusViewModel,
        template: htmlString
    };
});

1 个答案:

答案 0 :(得分:0)

setTimeout的第一个参数需要是将被调用的函数。正如所写......

setInterval(census.getCensus(requestUrl).then(onFulfilled, onRejected), 3000);
立即调用

... census.getCensus(...),并将返回的承诺传递给setTimeout

将它包装在一个函数中应该可以工作......

setInterval(function() { census.getCensus(requestUrl).then(onFulfilled, onRejected) }, 3000);

值得一提的是,使用then中的拒绝处理程序被认为是一种不好的做法;最好使用.then(onSuccess).catch(onRejected)