我正在編寫一個網頁,每4秒會發送一條不同的消息。我已經構建了一個自定義對象,我打算從中提取信息以創建要顯示的字符串。我使用的函數類似於Math.random,它叫做'rand',它可以讓我隨機訪問對象。我已經設置了4秒的時間間隔。我可以得到要顯示的字符串,但在此之後,網頁會繼續加載和加載,並且開始嚴重滯後以致不得不退出。我使用的代碼如下所示。請幫忙!需要JavaScript OOP和setInterval幫助
var name = "Barack Obama";
var Actions = {
"ActionList" : [
{ "action" : "watches a 30 minute TV show",
"time" : 30,
"time_measure" : "minute",
"assuming" : "assuming he sat through the commercials too"
},
{
"action" : "makes some pizza rolls",
"time" : 9,
"time_measure" : "minute",
"assuming" : "he only made one plateful"
},
{
"action" : "takes a 2 hour nap",
"time" : 2,
"time_measure" : "hour",
"assuming" : "assuming he's a heavy sleeper"
},
{
"action" : "1000 jumping jacks",
"time" : 1,
"time_measure" : "hour",
"assuming" : "he doesn't take a break, or slow down"
}
]
};
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function run() {
/**
* RANDOMLY SELECT OBJECTS
***/
var r = rand(0, 3);
var x = Actions.ActionList[r]["action"];
document.write(x);
}
setInterval(run, 4000);
接受了您的建議,但在編輯代碼後,我沒有從代碼中獲得任何輸出。 – JaPerk14
顯示你嘗試過的沒有使用document.write。 – epascarello