2016-09-20 26 views
1

比方說用戶正在點擊一個按鈕,並且時間,讓說0的Javascript /節點和定時

第一做與服務器片面的請求的事,是再次走的時候,可以說其0這個時間太長,存儲在一個名爲變種currenttime(與new Date().getTime()

那麼該服務器是工作,事情需要時間,直到它調用儲存的時間,給用戶一些等待時間的函數。

問題是,讓說IM發送變量CURRENTTIME的功能和將其保存,並增加了讓說90分鐘(1 1/2小時)。

然後客戶端雙面,即時檢索用戶需要等待的時間。 但在這種情況下,結果是90分鐘(和一些exs secs,在15-30s之間)。

我怎樣才能確保,從發送請求到服務器,用戶不需要等待時間超過90分鐘?

函數調用:

// after processing things this occurs 
    userData.updateTimers(userid, whattotime, 5400,currenttime); 

5400是5400秒,如90分鐘。 當前時間是變量new Date().getTime()檢索到的第一件事。

acual功能:

function updateTimers(userid,type,sec,time) { 
    return new Promise(function (resolve, reject) { 
     var newtime = time + (sec * 1000); 

     var updateObj = {}; 
     updateObj[type] = newtime; 

     usertimers.update({userid: userid},{$set: updateObj}).then(function (result) { 
      console.log("updated timers"); 
      console.log(result); 
      return resolve(result); 
     }) 
    }); 
} 
再次

,我怎樣才能使Sture專門的90分鐘,並且不包括處理時間? 我需要定時更新準確。

我在AngularJS前端使用了平均值堆棧。這是一個解決方法,需要花時間在那裏,並將其服務器側面爲將來使用,或者是我可以做的更好的東西?

因爲無論我做什麼服務器片面的,加上一些等待時間,這將永遠是一個幾秒鐘:/

+0

所以,如果我理解正確...你想讓你的函數'updateTimers'在不超過90分鐘的時間內結束嗎? – MinusFour

+0

從用戶實際點擊按鈕的時間開始,用戶確實需要等待更長的時間。 – maria

+0

如果因爲尚未完成處理或其他事情而需要比90分鐘更長的時間,那麼您會回答那個錯誤? – MinusFour

回答

0

使用watchdog蜱路程,測試對日期偏移。

你就可以發送的「完成」(new Date().getTime() + (1000 * 60 * 90))日期給用戶。

//Accurate timer using a watchdog 
 

 
var Watchdog = (function() { 
 
    function Watchdog(waitMilliseconds, callback) { 
 
     if (callback === void 0) { callback = function() { }; } 
 
     this.waitMilliseconds = waitMilliseconds; 
 
     this.callback = callback; 
 
     this.start = new Date().getTime(); 
 
     var self = this; 
 
     this.interval = setInterval(function() { self.test(); }, 1); 
 
    } 
 
    Watchdog.prototype.test = function() { 
 
     if (new Date().getTime() - this.start > this.waitMilliseconds) { 
 
      console.log(new Date().getTime() - this.start); 
 
      clearInterval(this.interval); 
 
      this.callback(); 
 
     } 
 
    }; 
 
    return Watchdog; 
 
}()); 
 

 
new Watchdog(1000, function() { 
 
    console.log("A second has passed"); 
 
}); 
 

 
new Watchdog(1000 * 60 * 90, function() { 
 
    console.log("90 minutes has passed"); 
 
});

+0

我也是這麼做的,但是我仍然得到了很少的exstra secs:/ – maria

0

如果我明白你的問題,你可以使用這樣的Promise.timeout

Promise.timeout = function(timeout, promise){ 
    return Promise.race([ 
    promise, 
    new Promise(function(resolve, reject){ 
    setTimeout(function() { reject('Timed out'); }, timeout); 
    }) 
]); 
} 

你會使用這樣的:

Promise.timeout(yourRequestFunctionWhenUserClicksButton(), 1000 * 90); //90 seconds 

基本上,如果請求持續超過90秒,它會返回被拒絕的承諾,否則將滿足從服務器回答的價值。