弹钢琴的键在JavaScript中的延迟后 [英] Playing piano keys after delay in JavaScript
问题描述
我试图写一个脚本来'玩'在这个在线键盘用JavaScript'点击'我的钥匙。
I was trying to write a script to 'play' some keys on this online keyboard by using JavaScript to 'click' the keys for me.
//sample array to iterate over
var keys_ = ['et', 'dst', 'et', 'dst', 'et', 'b', 'dt', 'ct', 'a', ...];
//handles the clicking only
function playKey(id_) {
key_ = document.getElementById(id_);
key_.click(); }
//iterates over the array
function playKeys(keys_) {
delay = 1000;
for (i = 0; i < keys_.length; i++) {
console.log(delay);
key_ = keys_[i];
console.log(key_);
window.setTimeout('playKey(key_)', delay);
delay += 1000;
}
}
输出
控制台引发以下错误:
The output
The console throws the following error:
1000结果
等结果
2000结果
DST结果
...结果
9000结果
一个结果
未定义的结果
未捕获类型错误:无法读取空对ano.html财产风格:142结果
8遗漏的类型错误:不能调用方法'点击'空的
1000
et
2000
dst
...
9000
a
undefined
Uncaught TypeError: Cannot read property 'style' of null p-ano.html:142
8 Uncaught TypeError: Cannot call method 'click' of null
正如你所看到的,延迟
和键_
值是完全正确的。不过还是当我执行这一点,一秒钟后(即1 ST 超时),所有的按键似乎玩一次,然后什么也没有发生。
As you can see, the delay
and key_
values are perfectly correct. But still when I execute this, after a second (i.e., the 1st timeout), all the keys seem to play at once and then nothing happens.
我在做什么错了?
的 P.S:我见过像<一个其他问题href=\"http://stackoverflow.com/questions/11492116/how-to-create-a-javascript-that-clicks-a-particular-url-after-a-certain-amount-o\">this 之一和谷歌搜索和其他论坛,都无济于事的
P.S.: I've seen other questions like this one and searched Google and other forums, to no avail
推荐答案
了解有关关闭。
window.setTimeout(function(){ playKey(key_); }, delay);
和你有全局和当地人的一个问题。使用VAR!
and you have a problem with globals and locals. Use var!
我会写这将是该办法
( 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();
})();
这篇关于弹钢琴的键在JavaScript中的延迟后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!