在循环中调用setTimeout不能按预期工作 [英] Calling setTimeout in a loop not working as expected

查看:118
本文介绍了在循环中调用setTimeout不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下JavaScript应该(在我看来)播放0.5秒的音符序列。但它将它们全部作为单个同时和弦播放。知道怎么解决吗?

The following JavaScript ought to (in my mind) play a sequence of notes 0.5 sec apart. But it plays them all as a single simultaneous chord. Any idea how to fix it?

function playRecording() {
    if (notes.length > 0) {
        for (var i = 0; i < notes.length; i++) {
            var timeToStartNote = 500 * i;
            setTimeout(playNote(i), timeToStartNote);
        }
    }
}

function playNote(i) {
    var noteNumber = notes[i];
    var note = new Audio("/notes/note_" + noteNumber + ".mp3");
    note.play();
}


推荐答案

实际上非常简单,在for循环你调用函数 playNote(i)它会瞬间播放音符(因此它会像一个和弦一样立即播放很多音符,因为它处于一个非常快速运行的循环中) 。相反,你应该试试这个让超时实际播放音符的代码。 setTimeout 函数需要将函数作为参数,而不是调用函数。

Very simple actually, in the for loop you call the function playNote(i) which plays the note i instantaneously (and therefore play many notes instantly like a chord since it is in a really fast running for loop). Instead you should try code this which lets the timeout actually play the note. The setTimeout function expects the function as an argument instead you called the function.

(function(j){setTimeout(function(){playNote(j);},j*500);}(i));

这篇关于在循环中调用setTimeout不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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