JavaScript: не могу остановить установку
-
20-09-2019 - |
Вопрос
Я работаю над проверкой прокси -сервера и имею следующий код, чтобы запустить запросы с интервалом примерно 5 секунд, используя функцию SetTimeout;
function check() {
var url = document.getElementById('url').value;
var proxys = document.getElementById('proxys').value.replace(/\n/g,',');
var proxys = proxys.split(",");
for (proxy in proxys) {
var proxytimeout = proxy*5000;
t = setTimeout(doRequest, proxytimeout, url, proxys[proxy]);
}
}
Однако я не могу остановить их, как только они начали!
function stopcheck() {
clearTimeout(t);
}
Исправление или лучший метод будет больше, чем ценится.
Спасибо сообщество переполнения стека!
Решение
Есть 2 основные проблемы с вашим кодом:
t
перезаписан для каждого тайм -аута, теряя ссылку на предыдущий тайм -аут каждую итерацию.t
может не быть глобальной переменной, таким образомstopcheck()
Может быть, не сможет "увидеть"t
.
Обновленные функции:
function check() {
var url = document.getElementById('url').value;
var proxys = document.getElementById('proxys').value.replace(/\n/g,',');
var timeouts = [];
var index;
var proxytimeout;
proxys = proxys.split(",");
for (index = 0; index < proxys.length; ++index) {
proxytimeout = index * 5000;
timeouts[timeouts.length] = setTimeout(
doRequest, proxytimeout, url, proxys[index];
);
}
return timeouts;
}
function stopcheck(timeouts) {
for (var i = 0; i < timeouts.length; i++) {
clearTimeout(timeouts[i]);
}
}
Пример использования:
var timeouts = check();
// do some other stuff...
stopcheck(timeouts);
Другие советы
Где определяется «t»? Он постоянно переопределяется в петле, так что вы будете терять каждую ручку времени ...
Вы можете сохранить множество ручек:
var aTimeoutHandles = new Array();
var iCount = 0;
for (proxy in proxys) {
var proxytimeout = proxy*5000;
aTimeoutHandles[iCount++] = setTimeout(doRequest, proxytimeout, url, proxys[proxy]);
}
Определять t
сначала вне обеих функций. Кроме того, вы перезаписываете t
с каждой итерацией ваша for
петля. Возможно, создание коллекции ссылок, а затем остановить их, вы пробегаете, и clearTimeout
на каждого.
Вы перезаписываете t
Каждый раз, когда вы устанавливаете интервал. Таким образом, вы только в конечном итоге очищаете последний набор.
Looks like you're setting multiple timeouts (one for each proxy), but trying to save them in the same variable. You probably need to use an array there, instead of a simple variable.
You have a few problems there:
- The main one is that you're overwriting
t
on each iteration of yourfor
loop; you need an array oft
s for your structure to work. - You're using
for..in
to loop through the indexes of the array. That's not whatfor..in
is for (although there are a lot of people confused about that; see this article).for..in
loops through the property names of an object, not the indexes of an array, and therefore this usage breaks in non-trivial situations. Just use an old-fashionedfor
loop. - You're declaring
proxys
twice. This is actually harmless, but... - You're not declaring
proxy
at all (which isn't harmless; it becomes an implicit global).
I've updated the code in Jordan's excellent answer to address those.