Playing piano keys after delay in JavaScript

泄露秘密 提交于 2019-12-06 11:06:16

Learn about closures.

window.setTimeout(function(){ playKey(key_); }, delay);

and you have a problem with globals and locals. Use var!

The way I would write it would be

( function() {
    var keys_ = ['et', 'dst', 'et', 'dst', 'et', 'b', 'dt', 'ct', 'a'],
        delay = 250,
        currentIndex = 0,
        playKeys = function () {
            document.getElementById(keys_[currentIndex]).click();        
            currentIndex++;
            if (currentIndex<keys_.length) {
                window.setTimeout(playKeys,delay);
            }    
        };    
    playKeys();
})();
Tina CG Hoehr

Huh? There's already a built-in function called playstr().

function playstr(instr) {
    keystr = instr;
    time = 0;
    k = 0;
    for (i = 0; i < keystr.length; i++) {
        setTimeout("playkbd(keystr[k])", time += 50);
        setTimeout("k++", time + 50);
        setTimeout("cb()", time += 200);
    }
}​

Try pressing 'z', 'x', or 'm' to run them.

if (key=="z")
  playstr("wetyuyuju     ujo..juyyuj..uyttfy..yuytft     ujp..o;poko     opoj..uy\
  uju     ujo..juyyuj..uyttfy..yuytft     w e t y u y uoj u ")

if (key=="x")
  playstr("tgtdtgtdtgghhgtdd              tgtdtgtdtgghhgtdd              djjjkjhh\
  jhghjhg djjjkjhhjhghjhg djjjkjhhjhghjhg djjjkjhhjh     tgtdtgtdtgghhgtdd")

if (key=="m")
  playstr("         k j y j k j y f e f e a e f y j k j y j k j y f e f e a e f y\
   j k j y j k j y f e f e a e f y j k j y j k j y f e f e a e f y j ")

I am running a mirror and want to know how to auto-play chords.

// F F 1 F A N F A R E 

if (key==".") {
  setTimeout("playstr('u y u yo ok ok ku y g yf   u y u yo ok ok ku y u op ')",100)
}

I am assuming the code you have posted is exactly what you are running. In this case the three dots are illegal.

keys_ = ['et', 'dst', 'et', 'dst', 'et', 'b', 'dt', 'ct', 'a', ...]

Try removing them like

keys_ = ['et', 'dst', 'et', 'dst', 'et', 'b', 'dt', 'ct', 'a']

Also, as a tip, try writing cleaner javascript. Use var before declaring variables. End your statements with ; semi-colons.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!