如何无限循环数据集字符串

时间:2012-08-16 16:28:11

标签: javascript jquery loops

我正在寻找一种方法来继续循环几个值。我正在使用一个简单的ajax加载脚本,它从目标元素的数据集中获取值(文件)。重新加载一个文件每隔XXXX一次,所以它会一遍又一遍地加载文件,但如果有更多的文件存在,它应该循环它们全部,并重新循环....无限

下面的例子是一个基本的想法,我分割字符串并从第一个开始,但我怎样才能循环(最好的方式),并保持循环。

HTML

<div id="target" data-load="file1.php | file2.php | file3.php"></div>

的jQuery

var fileTo = $('#target').data('widget-load').split("|");

setInterval(function(){
   $('#target').load(fileTo[0])
},1000);

4 个答案:

答案 0 :(得分:0)

你可以使用setTimeout(“function”,delay)继续在其自身内调用相同的函数,延迟时间为毫秒。

答案 1 :(得分:0)

@Diode:在无限循环的情况下,shift&amp;&amp;推是更好的选择。忘了他们。在这种情况下,我建议如下:

var intervalId = setInterval((function(theArray)
{
    var target = $('#target');
    var current;
    return function ()
    {
        current = theArray.shift();
        target.load(current);
        theArray.push(current);
    };
})($('#target').data('widget-load').split("|")),1000);

试试这个:

var intervalId = setInterval((function(theArray)
{
    var target = $('#target');//only search for this once, not on every call
    //to make infinite loop, copy the array
    var resetArr = theArray.slice(0);//use slice, if not a reference is assigned and both arrays will be altered 
    //Name is not required, if you want to use a name, pick a better one, next might be reserved (not sure)
    //best go for nextInterval, chose this one for explanation
    return function next()
    {
        //get first element, theArray is now 1 shorter
        target.load(theArray.splice(0,1)[0]);
        if (theArray.length === 0)
        {//no more files left -> this stops the interval
            //clearInterval(intervalId);
            //intervalId = null;
            //restore the array, the loop starts from file1 again --> infinite loop
            theArray = resetArr.slice(0);//copy the original value
        }
    }
})($('#target').data('widget-load').split("|")),1000);

这可能有点密集,但我在chrome console中尝试了一个简单的单行版本:

foo = setInterval((function(arr){ return function(){alert(arr.splice(0,1)[0]); if (arr.length === 0){ clearInterval(foo);}};})([1,2,3]),1000);

它就像一个魅力。
工作原理:

intervalId保存间隔的erm id ...类似于引用。只要设置了该函数,就会每1000ms调用该函数。我没有将简单函数作为第一个参数传递,而是创建了一个函数,并立即调用它。我传递给无名函数(theArray)的参数可以通过名为next的函数访问,该函数是匿名函数的返回值。它是在函数内创建的,因此即使在返回后,它也可以访问其函数的所有变量。
这意味着theArray的值除了next函数之外的其他任何地方都不在范围内,theArray函数是我们间隔的实际回调。没有什么可以干扰target的值,任何外部代码都不能覆盖任何东西,与使用全局变量相比,这是一种更安全的方法。
这同样适用于变量next:它是在匿名的函数中声明和初始化的,它被调用一次,然后调用GC。该变量仍然存在,并引用了一个jQuery对象。对于该元素,DOM只被搜索过一次,但是对next函数的每次新调用都可以访问该对象。这样做一次并且速度差异是微不足道的,一直这样做,你的脚本 会(更多)更有效率!

所以,间隔:每1000毫秒,theArray被调用。它将第一个值从作为其创建者(即匿名函数)的参数(clearInterval)的数组中移出。当该数组为空时,调用theArray函数来停止该批次。所有文件都已加载,没有任何意义继续。
一旦发生这种情况,nexttarget - 函数和所有其他变量((function() { var intervalId = setInterval((function(theArray) { //... })($('#target').data('widget-load').split("|")),1000); })(); )超出范围,所以没有全局,只是一个漂亮,干净的记忆块,这总是一件好事。我假设这个代码将作为事件处理程序的一部分被触发,在这种情况下,您可以将其粘贴到处理程序中,同样,不会创建全局变量。

如果此代码将成为全局范围的一部分,则可以通过将其全部包装在自动调用函数中来轻松避免全局变量:

{{1}}

你们都准备好了。恕我直言,这是解决这个问题的最好,最安全,最 JS-mindded 的方法。 JavaScript就是关于功能,你利用它们越多,语言就越喜欢它。事实上,通过揭示其隐藏的表现力,它会感谢你。

即使你决定不使用这个答案,也要阅读闭包等内容以及如何充分利用函数范围。您很快就会发现自己以全新的方式编写代码,并承诺:)

答案 2 :(得分:0)

var fileTo = $('#target').data('widget-load').split("|");

setInterval(function(){
   var file = fileTo.shift();   // `shift` gives the file at 0
   $('#target').load(file);     // load it
   fileTo.push(file);           // `push` adds it at the end of the array
},1000);

答案 3 :(得分:-1)

var $target = $('#target'),
    fileTo = $target.data('widget-load').split("|"),
    i = 0;

setInterval(function(){
   $target.load(fileTo[i]);
   i++;
   if (i === fileTo.length)
      i = 0;
},1000);
相关问题