JavaScript 如何等待调整大小事件的结束并执行操作
当我们调整浏览器窗口大小时,“resize”事件将连续触发多次。我们希望“resize”事件在完成调整大小后仅触发一次。
准备条件: 为了解决这个问题,我们使用了两个函数:
- setTimeout()函数
- clearTimeOut()函数
示例:使用 setTimeout() 函数,以便我们希望在调整大小后触发的函数等待500毫秒。现在,我们将setTimeout()函数放置在“resize”事件中。在 setTimeout() 之前,我们设置 clearTimeOut() 来清除该setTimeout()计时器。由于调整窗口大小时会连续触发resize事件,因此也会连续调用 clearTimeOut() 。因此,在停止调整大小之前,setTimeout()内部的函数不会运行。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<!-- div is used to display a message
when we are done resizing -->
<div id="message"></div>
</body>
</html>
JavaScript代码
<script>
// Message variable contains the div object which
// is used to display message after we are done resizing
var message = document.getElementById("message");
// timeOutFunctionId stores a numeric ID which is
// used by clearTimeOut to reset timer
var timeOutFunctionId;
// The function that we want to execute after
// we are done resizing
function workAfterResizeIsDone() {
message.innerHTML += "
<p>Window Resized</p>
";
}
// The following event is triggered continuously
// while we are resizing the window
window.addEventListener("resize", function() {
// clearTimeOut() resets the setTimeOut() timer
// due to this the function in setTimeout() is
// fired after we are done resizing
clearTimeout(timeOutFunctionId);
// setTimeout returns the numeric ID which is used by
// clearTimeOut to reset the timer
timeOutFunctionId = setTimeout(workAfterResizeIsDone, 500);
});
</script>
输出: