簡體   English   中英

window.variable 無法訪問

[英]window.variable can't be accessed

我正在嘗試創建一個網站,其中包含 ID 為“vid”的文本“游戲結束”,我希望它每 300 - 400 毫秒隨機化大寫和小寫,並在重置回小寫之前保持 40 毫秒. 這是我現在得到的代碼:(我的Javascript不是很好)

 setInterval(function() { window.smth = Math.floor((Math.random() * 100) + 1) + 300; var elem = document.getElementById('vid'); elem.textContent = "game over"; setTimeout(function() { elem.textContent = elem.textContent.split('').map(function(v) { var chance = Math.round(Math.random()); return v = chance ? v.toUpperCase() : v.toLowerCase(); }).join(''); }, window.smth); }, window.smth + 40);
 <div id="vid"></div>

除了最后兩行忽略“window.smth”外,一切正常。 我嘗試了不同的設置“smth”的方法,但我找不到一種與其他代碼循環並且可以在我使用它的任何地方訪問的方法。

因為window.smth是在回調中設置的,所以在設置interval的時候是undefined 即使您在第一次調用回調后定義smth ,它仍然不會工作,因為setInterval函數只被調用一次。

像這樣創建間隔的方法是多次超時; 偽代碼:

setTimeout(_ => {
  // do something

  setTimeout(..., otherTime) // you don't want to nest and nest and nest this, just create a function for this that's recursive
}, time)

您在第一個超時回調中聲明window.smith ,但在實際調用回調之前使用它。 所以最后一行的window.smith當時實際上還undefined

嘗試將window.smth定義從第一個回調中移出,如下所示:

window.smth = Math.floor((Math.random() * 100) + 1) + 300;
setInterval(function() {
  var elem = document.getElementById('vid');
  elem.textContent = "game over";
  setTimeout(function() {
    elem.textContent = elem.textContent.split('').map(function(v) {
      var chance = Math.round(Math.random());
      return v = chance ? v.toUpperCase() : v.toLowerCase();
    }).join('');
  }, window.smth);
}, window.smth + 40);

smthsetInterval()放入另一個:

 var smth = 500; setInterval(function() {smth = Math.floor((Math.random() * 100) + 1) + 300;}, 250); setInterval(function() { var elem = document.getElementById('vid'); elem.textContent = "game over"; setTimeout(function() { elem.textContent = elem.textContent.split('').map(function(v) { var chance = Math.round(Math.random()); return v = chance ? v.toUpperCase() : v.toLowerCase(); }).join(''); }, smth); }, smth);
 <div id="vid"></div>

暫無
暫無

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

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