javascript setTimeout在foreach:需要帮助创建一个闭包 [英] Javascript setTimeout in foreach: need help creating a closure

查看:674
本文介绍了javascript setTimeout在foreach:需要帮助创建一个闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能

notes.forEach(function(note) {          
    setTimeout(function() {
        playNote(note);
    }, 1000);
});

这不起作用。它同时播放所有的音符,而不是连续播放它们之间有1秒的间隙。看起来我需要一个闭包,使这项工作。有人可以帮我修复这个功能,所以它会播放音符与每个音符之间的延迟。

This doesn't work. It plays all the notes at the same time, instead of playing them sequentially with a 1 second gap in between. It looks like I need to have a closure here to make this work. Could someone help me fix this function so it would play the note with the delay between each note?

推荐答案

,因为所有的超时设置同时...

because all timeouts are set at the same time...

执行这样的操作:

playAllNotes(0);
function playAllNotes(index) {
    if(notes.length > index) {
        setTimeout(function() {
            playNote(notes[index]);
            playAllNotes(++index);
        }, 1000);
    }
}

这篇关于javascript setTimeout在foreach:需要帮助创建一个闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆