【问题标题】:Loop through set of items forwards and backwards with setTimeout使用 setTimeout 向前和向后循环遍历一组项目
【发布时间】:2014-08-23 23:42:06
【问题描述】:

这个让我头疼!

我有一个物品清单:

var prev = 'sally.charlie.ted';
var next = 'tina.heather.david';

然后我想向前和向后循环遍历它们,每个延迟 1 秒:

animate(prev, function () {
    animate(next, function () {
        console.log('done');
    }, false);
}, true);

但现在我让自己感到困惑。也许这些是更好的方法?

function animate(url, callback, reverse, index, length) {
    var items = url.split('.'),
        total = items.length - 1;
    if (typeof index === 'undefined') { index = reverse ? items.length - 1 : 0; }
    if (typeof length === 'undefined') { length = reverse ? url.length + items[index].length + 1 : 0; }
    if (index > total || index < 0) {
        callback();
    } else {
        if (reverse === true) {
            length -= items[index].length + (items.length - index);
        } else {
            length += items[index].length + index;
        }
        console.log(url.length, total, length, items[index], url.slice(0, length));
        window.setTimeout(function () {
            animate(url, callback, reverse, reverse ? index - 1 : index + 1, length);
        }, 1000);
    }
}

我想为每个项目获取正确的完整路径,无论是向前还是向后。我想要的向后输出是:

ted = sally.charlie.ted
charlie = sally.charlie
sally = sally

然后转发:

tina = tina
heather = tina.heather
david = tina.heather.david

这是一个有效的小提琴:

http://jsfiddle.net/kmturley/oco5uxrn/1/

【问题讨论】:

    标签: javascript loops animation settimeout


    【解决方案1】:

    我对你的代码做了一点改动。

    试试这个。

    function animate(url, callback, reverse, index) {
        var items = url.split('.'),
            length = 0;
        if (typeof index === 'undefined') { index = reverse ? items.length - 1 : 0; }
        if (index >= items.length || index < 0) {
            callback();
        } else {
            length = url.indexOf(items[index]) + items[index].length;
            console.log(url.length, items[index], url.slice(0, length));
            window.setTimeout(function () {
                animate(url, callback, reverse, reverse ? index - 1 : index + 1);
            }, 1000);
        }
    }
    

    运行它我得到了这个日志:

    17 "ted" "sally.charlie.ted"
    17 "charlie" "sally.charlie"
    17 "sally" "sally"
    18 "tina" "tina"
    18 "heather" "tina.heather"
    18 "david" "tina.heather.david" 
    

    【讨论】:

    • 很棒,而且更短!这困扰了我 3 个小时。你让我很开心,谢谢!
    • indexOf 是我缺少的功能,可以让这更容易,非常有用
    • 我更新了我的小提琴以反映您的更改并更改 if 语句周围的逻辑,使其更有意义:jsfiddle.net/kmturley/oco5uxrn/3
    猜你喜欢
    • 1970-01-01
    • 2019-08-10
    • 2012-01-22
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    相关资源
    最近更新 更多