在Coffeescript中编写递归的setTimeout循环

Rya*_*lio 4 javascript jquery coffeescript

我正在制作一个实时照片流应用.基本上,用户将通过FTP将照片上传到我的服务器上的文件夹,并且只要添加新照片而不刷新,页面就会更新.

我打算用AJAX和这个线程中建议的方法来做这个:如何用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);

});
Run Code Online (Sandbox Code Playgroud)

我在这个项目上使用Coffeescript试图了解它是如何工作的,因为很多开发人员似乎都喜欢它,但我无法弄清楚如何在不使用命名函数的情况下复制这个功能.有人可以指出我正确的方向或解释一个更好的方式让我实现这种效果,可以在Coffeescript轻松完成?

小智 6

一个更简洁的版本

do poll = ->
  #do work here
  setTimeout poll, 1000
Run Code Online (Sandbox Code Playgroud)

编译成

var poll;
(poll = function() {
  //do work here
  return setTimeout(poll, 1000);
})();
Run Code Online (Sandbox Code Playgroud)