快速调用时显示最短时间的标签会中断

Showing a label for a minimum amount of time breaks when called quickly

单击按钮时我会显示一个通知标签,它工作正常,但如果我多次按下按钮,有时通知会立即消失。

var duration = 3000;

function showNotificationLabel() {
    var date = new Date();
    var time = date.toLocaleTimeString();

    messageLabel.textContent = "Task Complete at " + time;

    setTimeout(() => {
      messageLabel.textContent = "";
    }, duration);
  }
body {
  font: caption;
}
<p>
  <span id="messageLabel"></span>&nbsp;
</p>

<div>
  <button onclick="showNotificationLabel()">Start</button>
</div>

如何确保标签不会在超时发生前消失?

这是因为每次点击,都会发起一个新的独立超时,使用相同的回调函数。

为防止这种情况,您应该清除之前的每次点击超时:

https://www.w3schools.com/jsref/met_win_cleartimeout.asp

var duration = 3000;
var timeOutRef = null;

function showNotificationLabel() {
    var date = new Date();
    var time = date.toLocaleTimeString();

    messageLabel.textContent = "Task Complete at " + time;

    if(timeOutRef != null) clearTimeout(timeOutRef);

    timeOutRef = setTimeout(() => {
      messageLabel.textContent = "";
    }, duration);
  }
body {
  font: caption;
}
<p>
  <span id="messageLabel"></span>&nbsp;
</p>

<div>
  <button onclick="showNotificationLabel()">Start</button>
</div>