我正在处理实时照片流应用程序。实质上,用户将通过FTP将照片上传到服务器上的文件夹,并且每次添加新照片时页面都应该更新而不刷新。在Coffeescript中编写递归setTimeout循环
我打算使用AJAX和本主题中建议的方法执行此操作:How to check if directory contents has changed with PHP?。从本质上讲,我希望在我的页面上有一个循环,每隔X秒,对一个PHP页面进行AJAX调用,该页面为上传文件夹提供目录列表的MD5哈希值。如果自上次调用后散列值发生了变化,则另一个AJAX调用将获得最近添加的文件,并且jQuery将在页面上显示它。
在vanilla Javascript/jQuery中,可以使用一个带有setTimeout的递归命名函数完成。此代码为我工作:
function refreshLoop(currentFolderState, refreshRate) {
// Get the new folder state
$.get("../ajax/getFolderState.php", function(data) {
// If it's different than the current state
if (data !== currentFolderState) {
// Do something
}
// If it's the same as the current state
else {
// Do nothing
}
// After the refresh rate, try again
setTimeout(function() {
refreshLoop(data, refreshRate);
}, refreshRate);
});
}
// Document Ready
$(function() {
var refreshRate = 5000;
// After refresh rate has passed
setTimeout(function() {
// Get the starting folder state
$.get("../ajax/getFolderState.php", function(data) {
// Kick off the loop
refreshLoop(data, refreshRate);
});
}, refreshRate);
});
我使用的CoffeeScript在这个项目上,试图了解它是如何工作的,因为很多开发商似乎喜欢它,但我想不出如何在不使用命名函数的情况下复制此功能。某人能否指引我朝着正确的方向发展,还是解释一种更好的方式来实现这种可以在Coffeescript中轻松完成的效果?
我可以发誓我在某个时候尝试过这样做,但它不起作用,但我想我还有其他的犯规。谢谢! – 2012-03-08 20:51:44
@Ryan:你可能省略了额外的圆括号,CoffeeScript的隐含块结构有时会造成一些混乱。 – 2012-03-08 21:13:53
完美。内联功能已准备就绪。未来的读者,如果你在'f ='函数内使用任何'@'引用,你可能想更新它到'(=>',这样它就能正确捕获原始范围。 – 2016-06-16 18:51:20