繁体   English   中英

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

[英]Stop function from re- executing for one second with 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);
  }
};

这一目标将实现:

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

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

run();

上面的代码每1秒钟运行一次,但是如果您要确保在决定之前不能再次运行该函数,则可以改用如下标志:

let canExecute = true;
function run () {
  if (canExecute) {
    console.log('Im running');
    canExecute = false;
    pause(1000);
  }
};

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

run();
run();
run();
setTimeout(() =>{
  run();
}, 2000)

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

尝试使用下划线的节流阀( http://underscorejs.org/#throttle )或反跳( http://underscorejs.org/#debounce ),其中一种应符合您的需求

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM