如何在新调用上结束上一个函数调用


<html><head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script>
    $( window ).on( "load", function() {
        myfunc();
    });
    $(window).resize(function() {
        clearTimeout(this.id);
        this.id = setTimeout(myfunc, 200);
    });
    function myfunc(){
        $( "#myid" ).click(function() {alert('Hello');});
    }
</script>
</head><body>
<img src="https://assets.servedby-buysellads.com/p/manage/asset/id/32054" id="myid">
</body></html>

使用浏览器中的最小化和展开按钮。第一次调整大小后,单击图像,您将看到两个警报。第二次调整大小后,您将看到三个警报,依此类推。如何在新调用上结束上一个函数调用以仅查看上次调用myfunc()的警报?我需要这种调整大小检测方式,因为我需要在调整大小后立即更改其他元素上的某些元素。

每次调整窗口大小时,都会调用 myfunc 函数,该函数注册相同的回调匿名函数,该函数一遍又一遍地显示警报。

相反,为显示alert的函数指定一个名称,注册单击函数,该函数调用仅显示一次alert的单独命名函数,并根据需要调用它:

function showAlert(){
  alert('Hello');
}
$(window).on("load", function(){
  // Separate the code that actually produces the alert
  // so it can be called as needed.
  $("#myid").on("click", showAlert);
  showAlert();
});
$(window).resize(timer);
function timer() {
  clearTimeout(this.id);
  this.id = setTimeout(showAlert, 200);
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>
<img src="https://assets.servedby-buysellads.com/p/manage/asset/id/32054" id="myid">

问题是调整大小功能会触发多次,您可以通过在调整大小函数中执行console.log("Handler for .resize() called.");来了解自己,因此您将了解发生了什么,以及为什么会发生。

可以解决此问题的简单修复方法是使用setInterval()函数。

jQuery(document).ready(function($){
  $(window).on( "load", function() {
    myfunc();
  });
  $(window).resize(function() {
    var loop = setInterval(myfunc, 30);
    clearInterval(loop);
  });
  function myfunc(){
    $("#myid").click(function(){
    	alert('Hello');
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://assets.servedby-buysellads.com/p/manage/asset/id/32054" id="myid">

我认为这是不可能的。

Javascript通常不能异步工作。虽然它可以要求浏览器发送数据并传递回调函数,但任何回调往往只有在其他所有事情都完成时才会被取消,比如事件。我想结束您需要的函数执行从函数返回。

当堆栈上有新功能时,无法从堆栈中弹出函数。

最新更新