0

我有一个对象 ,toKeep其中每个对象的标签属性中都包含一个 MIDI 音符。

我希望它在一定延迟后播放,具体取决于收到的音符数量。

现在的问题是变量pinned_neighbor保持不变,即使它应该改变。

setTimeout函数没有接收到数据的问题吗?

for (var ed = 0; ed < toKeep.length; ed++) {
    var pinned_neighbor = toKeep[ed].label

    if (pinned_neighbor != undefined) {
        setTimeout(function(pinned_neighrbor) {

            output.playNote(pinned_neighbor, parseInt(midi.substr(2, 2)));
            output.stopNote(pinned_neighbor, parseInt(midi.substr(2, 2)), { time: "+" + Math.floor(timefloor / toKeep.length) });
            console.log('playing an edge note ' + pinned_neighbor + ' at ' + timecodea + ' on ' + parseInt(midi.substr(2, 2)));
            timecodea = timecodea + Math.floor(timefloor / toKeep.length);

        }, timecodea);
    }
}
4

1 回答 1

0

您没有将 pinned_neighbor 传递给 setTimeout,并且您不能按照当前编写代码的方式(据我所知)这样做。

您需要使用某种闭包来保留pinned_neighbor. 您可以使用 IIFE,也可以创建另一个调用setTimeout.

IIFE 方法

for (...) {
    var pinned_neighbor = ...;
    if (pinned_neighbor != undefined) {
        // pn comes from the parameter pinned_neighbor passed at the bottom
        (function (pn) {
            setTimeout(function () {
                // Play note, etc
            }, timecodea);
        // Captures the value of pinned_neighbor
        })(pinned_neighbor);
    }
}

分离功能

function playNote(pinned_neighbor, toKeepLength) {
    setTimeout(function () {
        // Play note using pinned_neighbor, etc
    }, timecodea);
}

// In your for loop
var pinned_neighbor = ...
if (pinned_neighbor != undefined) {
    playNote(pinned_neighbor, toKeep.length);
}
于 2019-12-26T04:46:50.027 回答