javascript - 使用 settimeout 停止函数重新执行一秒钟

标签 javascript settimeout

我想阻止我的函数在上次执行后一秒钟内重新执行。我已经尝试过下面的方法,但它不起作用。

function displayOut() {
	
	// images
	document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
	// Diologue box
	diologueBox.innerHTML = ""; // Clear Box
	teleTyperDiologue(db.rooms[roomLoc].description + 
		" The room contains: " +
			(function() {
				let x = "";
				for (let i = 0; i < db.items.length; i++) {
					if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
						x += db.items[i].name + ", "
					}
				}
				x = x.slice(0, x.length -2);
				if (x === "") {
					x = " nothing of special interest";
				}
				return x;
			})()
		+ ".");
	pause();
};

function pause() {
	setTimeout(function() {
		// Wait one second!
	}, 1000);
}

最佳答案

您可以使用这样的模式:

var executing = false;

function myFunc() {
  if(!executing) {
    executing = true;
    
    //Code
    console.log('Executed!');
    //End code
    
    setTimeout(function() {
      executing = false;
    }, 1000);
  }
}

setInterval(myFunc, 100);

所以在你的情况下,这看起来像这样:

var executing = false;

function displayOut() {
  if(!executing) {
    executing = true;

    // images
    document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
    // Diologue box
    diologueBox.innerHTML = ""; // Clear Box
    teleTyperDiologue(db.rooms[roomLoc].description + 
    " The room contains: " +
    (function() {
      let x = "";
      for (let i = 0; i < db.items.length; i++) {
        if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
          x += db.items[i].name + ", "
        }
      }
      x = x.slice(0, x.length -2);
      if (x === "") {
        x = " nothing of special interest";
      }
      return x;
    })()
    + ".");

    setTimeout(function() {
      executing = false;
    }, 1000);
  }
};

关于javascript - 使用 settimeout 停止函数重新执行一秒钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42978291/

相关文章:

JavaScript setTimeout 不起作用

JavaScript 暂停

javascript - Javascript 中的嵌套循环快捷方式?

javascript - 从 javascript 到片段着色器的单色

javascript - 如何使用 Angular JS 对 json 数组中的前 5 个元素进行排序和选择

javascript - 检查按钮是否在时间内被点击

javascript - 使用 jQuery 的具有相同键和不同值的对象数组

javascript - 如何检查 div 是否包含某个单词并检查该单词是否与 var 匹配?

jQuery 防止快速点击

javascript - 运行 setTimeout 并更改时间值