以下代码工作正常唯一的问题是click事件排队,例如每次点击都会调用setTimeout,弹出窗口会出现多次。如何使弹出窗口仅在用户点击时出现,并确保每个弹出窗口之间的差距为4秒
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);
答案 0 :(得分:4)
这称为功能限制:
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!");
在你的情况下,它将是:
window.onclick = throttle(popup);
我的语法可能有点复杂(ES6),所以让我们解释一下:
return function(...args){
返回一个新函数,它将所有参数存储在args数组中(这样我们就可以将它传递给内部函数)
if(!timeout)
如果没有超时
func(...args),
调用该函数,将我们的args数组作为参数传递(称为扩展运算符)
timeout=setTimeout(...,4000)
将我们的超时设置为在4000之后执行以执行以下操作:
_=>timeout=null
超时结束后,重置超时并等待下一个函数调用...
答案 1 :(得分:0)
Lodash有一个throttle功能。
_.throttle(func, [wait=0], [options={}])
答案 2 :(得分:0)
以下代码在不使用节流
的情况下解决了问题// JavaScript文档
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 ()
{
if (check === false)
{
return;
}
else 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;
setTimeout(checkValue , seconds);
}
}
}
}
function checkValue ()
{
showpopup = 1;
check = true;
}
window.onclick = popup;