Javascript:如何停止点击事件排队? [英] Javascript: how to stop the click event queuing?

查看:82
本文介绍了Javascript:如何停止点击事件排队?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码工作正常唯一的问题是click事件排队,例如每次点击都会调用setTimeout,弹出窗口会出现多次。如何使弹出窗口仅在用户点击时出现,并确保每个弹出窗口之间的差距为4秒

The following code works fine the only problem is that the click event get queued like for example the setTimeout gets called for each click and the popup appears multiple times. How to make the popup appear only when user clicks and to ensure that gap between each popup is lets say 4 seconds

var showpopup = 1;
var check = true;
var seconds = 4000;             // change the frequency here current frequency = 2 seconds
var url = "https://www.fb.com"; // change the url here
var strWindowFeatures = "toolbar=yes,scrollbars=yes,resizable=yes,top=0,left=0,width=" +screen.width 
                         + ",height=" +screen.height;
function popup (event)
{   
     event.stopPropagation();
     if (showpopup === 1)
     {
          //if 
(navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Windows 
Phone|Opera Mini|IEMobile/i))
          //{
                if (check == true)
                {
                      window.open(url , '_blank' , strWindowFeatures);
                      showpopup++;
                      check = false;
                }
          //}
     }
     else
     {
         setTimeout(checkValue, seconds);   
     }
}

function checkValue ()
{
    showpopup = 1;
    check = true;
}

window.onclick = popup(event);


推荐答案

这称为功能限制

function throttle(func){
  var timeout=null;
  return function(...args){
    if(!timeout) func(...args), timeout=setTimeout(_=>timeout=null,4000);//if were not waiting, execute the function and start waiting
  }
}

所以你可以执行

var alert=throttle(window.alert);

alert("Wohoo!");
alert("Never executed!");

在您的情况下,它将是:

In your case it would be:

window.onclick = throttle(popup);






我的语法可能有点复杂(ES6) ,让我们解释一下:


My Syntax is maybe a bit complicated (ES6), so lets explain it a bit:

return function(...args){

返回一个新函数,它存储args数组中的所有参数(这样我们就可以将它传递给我们的内部函数)

return a new function that stores all arguments in the args Array ( So that we can pass it to our inner function)

    if(!timeout) 

如果没有超时

func(...args), 

调用函数,将我们的args数组作为参数传递(称为扩展运算符)

call the function, passing our args array as parameters ( called spread operator)

timeout=setTimeout(...,4000)

设置执行超时4000之后执行以下操作:

set our timeout to execute after 4000 to execute the following:

_=>timeout=null

当超时结束时,重置超时并等待下一个函数调用...

When the timeout finishes, reset the timeout and wait for the next function call...

这篇关于Javascript:如何停止点击事件排队?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆