Javascript代码仅在调试时运行 [英] Javascript code runs only when debugging
问题描述
我正在使用Twitch api来检查所选频道是在线还是离线.有一个奇怪的错误.仅当在开发工具中调试脚本时,代码才起作用.我有什么想念的吗?
I am on using Twitch api to check if selected channels are online or offline. Having a weird bug. Code works only when debugging the script in dev tools. Am I missing anything?
$(document).ready(function() {
var channels = ["OgamingSC2","sheevergaming", "ESL_SC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
for (var i = 0; i < channels.length; i++) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + channels[i] + '?callback=?', function(data) {
if (data.stream) {
$('.wrapper li').eq(i).css('background-color', "blue");
} else {
$('.wrapper li').eq(i).css('background-color', "red");
}
});
};
})
这是完整代码 http://codepen.io/nikasv/pen/GqRMXq
推荐答案
$.getJSON()
是异步的.因此,它的完成回调在一段时间后被调用.您的for
循环运行到结尾,然后在调用回调时,将i
设置为for
循环的结尾.
$.getJSON()
is asynchronous. As such, it's completion callback is called some time later. Your for
loop runs to the end and then when the callback is called, i
is set to the end of the for
loop.
调试可能会改变事情的时机.
Debugging may changing the timing of things.
您可以通过将循环计数器嵌入到IIFE中来解决问题,这样对于for
循环的每次迭代它都会被唯一捕获,如下所示:
You can fix things by embedding the loop counter in an IIFE so it will be uniquely captured for each iteration of the for
loop like this:
$(document).ready(function() {
var channels = ["OgamingSC2","sheevergaming", "ESL_SC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
for (var i = 0; i < channels.length; i++) {
(function(index) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + channels[index] + '?callback=?', function(data) {
if (data.stream) {
$('.wrapper li').eq(index).css('background-color', "blue");
} else {
$('.wrapper li').eq(index).css('background-color', "red");
}
});
})(i);
}
});
或者,您可以使用.forEach()
为您提供内部功能:
Or, you can use .forEach()
which makes the inner function for you:
$(document).ready(function() {
var channels = ["OgamingSC2","sheevergaming", "ESL_SC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
channels.forEach(function(item, index) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + item + '?callback=?', function(data) {
if (data.stream) {
$('.wrapper li').eq(index).css('background-color', "blue");
} else {
$('.wrapper li').eq(index).css('background-color', "red");
}
});
});
});
这篇关于Javascript代码仅在调试时运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!