简单场景
我有一个列表,我实现了使用箭头键(向上、向下)进行浏览,并且在当前列表项的每次更改时,都会通过 AJAX 加载一个数据库对象。
甜蜜的。
问题
当用户快速浏览列表时,我不希望每个请求都关闭。但当然,最初的请求应该立即关闭。
我的想法是使用变量作为延迟来设置超时,并在项目初始加载后增加该变量。
这行得通,但是当用户暂时停止浏览但随后继续浏览时,我仍然不希望每个请求都关闭。
所以我想,延迟变量必须随着每次浏览事件而合理增加,直到达到阈值。
这种有机的方法将成功地减少不必要的元素加载量。
我的解决方案
我来得很远。这段代码(下面的解释)将完成这项工作,有一个主要罪魁祸首:
第一次浏览完成然后停止后,延迟将自动保持在(第 2 步)最小值 150 毫秒。
当然,我试图解决这个问题,但正如您将看到的,这是一个有趣但可能相当普遍的逻辑问题——我认为我的整体方法是错误的。
但是我不知道怎么办。大脑不计算。电脑说不。
代码
您可以筛选我给出的示例或 go here for a fully functional simulator in jsFiddle .
如果您选择 jsFiddle:
点击按钮,项目负载立即出现。现在稍等一下,再次单击按钮,初始加载将延迟。如果您连续快速按下按钮,则只有在您完成点击后才会显示项目加载。
代码示例
如你所知,我们在对象字面量中。
_clickTimer: false, // holds what setTimeout() returns
_timerInc: 0, // the your timer delay are belong to us
/**
* Function is triggered whenever the user hits an arrow key
* itemRef is the passed list item object (table row, in this case)
*/
triggerItemClick: function(itemRef){
var that=this;
var itemId=$(itemRef).data('id'); // Get the item id
if(this._clickTimer){ // If a timeout is waiting
clearTimeout(this._clickTimer); // we clear it
this._itemClickTimer=false; // and reset the variable to false
/**
* Note that we only arrive here after the first call
* because this._clickTimer will be false on first run
*/
if(this._timerInc == 0){ // If our timer is zero
this._timerInc = 150; // we set it to 150
} else { // otherwise
if(this._timerInc <= 350) // we check if it is lower than 350 (this is our threshold)
this._timerInc += 15; // and if so, we increase in steps of 15
}
}
/**
* Regardless of any timing issues, we always want the list
* to respond to browsing (even if we're not loading an item.
*/
this.toggleListItem(itemId);
/**
* Here we now set the timeout and assign it to this._clickTimer
*/
this._clickTimer=setTimeout(function(){
// we now perform the actual loading of the item
that.selectItem(itemId);
// and we reset our delay to zero
that._timerInc=0;
}, this._timerInc); // we use the delay for setTimeout()
}
解释
第一次调用时:_clickTimer 为 false,_timerInc 为 0,因此第一次调用将导致setTimeout() 和 _clickTimer 的延迟 0 将被设置。该项目将立即加载。
第二次调用 - 鉴于我们的超时仍在等待触发,_clickTimer 被清除,延迟设置为 150 如果 0如果低于 350(阈值),则增加 15。
如果您继续浏览,这会非常有效。计时器增加,只有在您停止浏览一段时间后才会触发负载。
但是在你停止之后,下次继续时,_clickTimer将不为false(因为setTimeout() 为其分配一个计数器),因此 _timerInc 将立即设置为 150。因此,第一次浏览将导致在加载任何内容之前有 150 毫秒的延迟。
不管我是疯了还是挑剔,但我的目标是不要有这种延迟。
当然你会说:很简单,在 setTimeout() 闭包结束时将 _clickTimer 设置为 false,这样一旦浏览完成它就会被重置,并且项目被加载。很好,但这导致延迟永远不会超过 0 毫秒。仔细想想,您就会明白。
我希望这得到了正确的解释,并且有人的大脑比我的更有能力找到解决方案。
最佳答案
使用 Promises 以非常复杂的方式执行此操作可能是可能的.由于这主要是糖衣,但我认为一定可以直接解决这个问题,我想我做到了。
Updated fiddle .我在文本中添加了延迟,这样我调试东西就更容易了,也做了一些小的整理,但我的实际变化很小。详情如下。
你最后的话是我的第一直觉:
Of course you'll say: simple, set
_clickTimerto false at the end of thesetTimeout()closure, so it gets reset once browsing is done and an item gets loaded. Great, but this results in the delay never going above 0ms.
确实,这将使延迟永远不会超过 0,因为我们不能那么快地单击(或在您的实际应用程序中快速浏览)。但是...如果我们只在延迟不为 0 时才重置 怎么办?因此,如果超时结束,但仅在 0 毫秒后结束,我们就会记住有超时。如果它晚于此关闭,则浏览中一定发生了实际暂停。这很容易实现,只需在超时回调中添加几行,如下所示。
this._clickTimer = setTimeout(function() {
// we now perform the actual loading of the item
that.selectItem();
// and we reset our delay to zero
if (that._timerInc > 0) {
that._clickTimer = false;
}
that._timerInc = 0;
}, this._timerInc); // we use the delay for setTimeout()
它似乎完全按照您想要的方式工作,除了现在,延迟将为 0 毫秒,然后是 150 毫秒,然后是 0 毫秒,等等,如果您在点击之间等待足够长的时间。这可以通过添加额外的超时来解决,以防延迟是 0ms,这仍然会重置延迟。每当触发发生时(在演示中单击,在您的应用程序中浏览),此超时将被取消。
我相信,这一切都可以按照您想要的方式运行。为了完整起见,我还将上面提到的 fiddle 作为片段包含在此处。
var _simulator = {
_clickTimer: false, // holds what setTimeout() returns
_cancelClickTimer: false,
_timerInc: 0, // the your timer delay are belong to us
/**
* Function is triggered whenever the user hits an arrow key
* itemRef is the passed list item object (table row, in this case)
*/
triggerItemClick: function() {
var that = this;
// always cancel resetting the timing, it can never hurt
clearTimeout(that._cancelClickTimer);
that._cancelClickTimer = false;
if (this._clickTimer) { // If a timeout is waiting
clearTimeout(this._clickTimer); // we clear it
this._clickTimer = false; // and reset the variable to false
/**
* Note that we only arrive here after the first call
* because this._clickTimer will be false on first run
*/
if (this._timerInc == 0) { // If our timer is zero
this._timerInc = 150; // we set it to 150
} else { // otherwise
if (this._timerInc <= 350) // we check if it is lower than 350 (this is our threshold)
this._timerInc += 15; // and if so, we increase in steps of 15
}
}
/**
* Regardless of any timing issues, we always want the list
* to respond to browsing (even if we're not loading an item.
*/
this.toggleListItem();
/**
* Here we now set the timeout and assign it to this._clickTimer
*/
this._clickTimer = setTimeout(function() {
// we now perform the actual loading of the item
that.selectItem();
// and we reset our delay to zero
if (that._timerInc > 0) {
that._clickTimer = false;
} else {
that._cancelClickTimer = setTimeout(function() {
that._clickTimer = false;
}, 150);
}
that._timerInc = 0;
}, this._timerInc); // we use the delay for setTimeout()
},
/** the following functions are irrelevant for the problemsolving above **/
toggleListItem: function() {
$('#status').prepend($('<div />').text('You toggled a list item ... in ' + this._timerInc + ' ms'));
},
selectItem: function(id) {
$('#loader').show();
setTimeout(function() {
$('#loader').hide();
}, 800);
}
};
$('#clickZone').on('click', function() {
_simulator.triggerItemClick();
});#clickZone {
background: #369;
color: #fff;
width: 420px;
height: 80px;
text-align: center;
line-height: 80px;
cursor: pointer;
-ms-user-select: none;
-moz-user-select: -moz-none;
-webkit-user-select: none;
user-select: none;
font-family: Arial;
}
#status {
line-height: 20px;
margin-top: 10px;
font-family: Arial;
font-size: 12px;
background: #936;
color: #fff;
padding: 7px 10px;
}
#status > div {
padding: 2px 0 4px;
border-bottom: 1px dashed #ddd;
}
#status > div:last-child {
border-bottom: 0;
}
#loader,
#notice {
display: none;
margin-top: 10px;
width: 320px;
padding: 10px 15px;
background: #ddd;
font-family: Arial;
font-size: 11px;
text-align: center;
}
#notice {
background: lightblue;
font-size: 14px;
color: #333;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickZone">
CLICK ME TO SIMULATE LIST BROWSING
</div>
<div id="loader">
✓ Browsing ended, loading item!
</div>
<div id="status">
<div>
Waiting for something to happen ...
</div>
</div>
关于javascript - 使用箭头键和智能延迟加载实现有机列表浏览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42573225/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po