使用settimeout停止功能重新执行一秒钟

时间:2017-03-23 14:01:12

标签: 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);
}
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

你可以使用这样的模式:

&#13;
&#13;
var executing = false;

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

setInterval(myFunc, 100);
&#13;
&#13;
&#13;

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

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);
  }
};

答案 1 :(得分:0)

这个将实现:

from collections import Counter
counted = Counter([7, 4, 2, 4, 9, 6, 5, 6, 2, 0, 2, 1])
ordered = [value for value, count in counted.most_common()]
print(ordered)  # [2, 4, 6, 0, 1, 5, 7, 9]

上面的代码每1秒运行一次,但是如果你想确保函数不能再次运行,那么你可以使用一个标志来代替:

function run () {
  console.log('Im running');
  pause(1000);
};

function pause(s) {
  console.log('Im paused');
  setTimeout(() =>{
    run();
  }, s)
};

run();

此代码将执行两次运行功能,首先按时执行,然后在2秒后再执行一次。

答案 2 :(得分:0)

尝试从下划线使用油门(http://underscorejs.org/#throttle)或去抖(http://underscorejs.org/#debounce),其中一个应该符合您的需求