簡體   English   中英

使用setInterval時,變量不會在全局范圍內更新

[英]Variable doesn't update in global scope when using setInterval

我想編寫一個函數,該函數將返回一個可以在另一個函數中使用的變量。 另一個功能應該使用當前時間和其他選定時間之間的時間比較。 我想可以通過使用return和property使時間變量在全局范圍內可訪問,並通過使用setInterval()對其進行更新。

不幸的是,當我將變量“導入”到另一個函數時,時間變量沒有更新。

為什么不console.log('time cool outside' + obj.debug ); 返回與console.log('time cool inside' + timeCool);相同的值console.log('time cool inside' + timeCool);

function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
  }

function timeFunction() {
  let today = new Date();
  let hours = today.getHours();
  let minutes = today.getMinutes();
  minutes = checkTime(minutes);
  hours = checkTime(hours);
  let stringHours = hours.toString();
  let stringMinutes = minutes.toString();
  time = stringHours + stringMinutes;
  let timeCool = parseInt(time);
  console.log('time cool inside' + timeCool);
  return {
    debug: timeCool,
  };

}
let obj = timeFunction();
setInterval(timeFunction, 5000);
function a() {console.log('time cool outside' + obj.debug );}
setInterval(a, 5000);

在行中

let obj = timeFunction();
setInterval(timeFunction, 5000);

您創建一個全局對象obj並將其設置為timeFunction的輸出。 然后使用setInterval定期調用timeFunction ,但不要將obj設置為其輸出。 因此,當a訪問obj它永遠不會改變

讓我們在這里看看你在做什么:

let obj = timeFunction();

在這里,您調用timeFunction並將其結果存儲到obj

setInterval(timeFunction, 5000);

在這里,您每5秒調用一次timeFunction 返回值被取消。

function a() {console.log('time cool outside' + obj.debug );}

在這里,您有一個引用之前定義的obj變量的新函數。 obj是對timeFunction的第一次調用的返回值,並且從未更改,因此無論您調用這兩個函數中的任何一個的頻率如何,它始終具有相同的值。

如果要更新obj ,則需要在timeFunction內部進行timeFunction或繼續將其設置為timeFunction的返回值。

謝謝你們的幫助。 確實,我沒有注意到我沒有更新“ obj”變量。

實施此之后:

let obj;
function objUpdate() {
obj = timeFunction();
}
setInterval(objUpdate, 1000);

一切看起來都像我想要的:)謝謝大家!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM