Глядя на то, что вы можете сделать с потоком, вы видите, что у него есть метод stop. Тем не менее, вы также увидите, что это устарело. Изучение объяснения его устаревания проясняет:
* @deprecated This method is inherently unsafe. Stopping a thread with
* Thread.stop causes it to unlock all of the monitors that it
* has locked (as a natural consequence of the unchecked
* <code>ThreadDeath</code> exception propagating up the stack). If
* any of the objects previously protected by these monitors were in
* an inconsistent state, the damaged objects become visible to
* other threads, potentially resulting in arbitrary behavior. Many
* uses of <code>stop</code> should be replaced by code that simply
* modifies some variable to indicate that the target thread should
* stop running. The target thread should check this variable
* regularly, and return from its run method in an orderly fashion
* if the variable indicates that it is to stop running. If the
* target thread waits for long periods (on a condition variable,
* for example), the <code>interrupt</code> method should be used to
* interrupt the wait.
* For more information, see
* <a href="{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
* are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
Следовательно, у вас должна быть проверка в вашем потоке, как у вас: ваша переменная end
. Обновите его в блоке finally, и ваш поток естественным образом достигнет конца своего выполнения.
Этот код должен сделать все, что Вы ищете; это базируется очень свободно на примере tj111. Я пытался сделать его максимально допускающим повторное использование, и этому не нужен JavaScript, смешанный в с HTML.
Действительно необходимо добавить идентификаторы к кнопкам (btnUP
и btnDOWN
) и текстовое поле (amount
). Можно изменить эти идентификаторы в window.onload
оператор.
// This function creates a closure and puts a mousedown handler on the element specified in the "button" parameter.
function makeButtonIncrement(button, action, target, initialDelay, multiplier){
var holdTimer, changeValue, timerIsRunning = false, delay = initialDelay;
changeValue = function(){
if(action == "add" && target.value < 1000)
target.value++;
else if(action == "subtract" && target.value > 0)
target.value--;
holdTimer = setTimeout(changeValue, delay);
if(delay > 20) delay = delay * multiplier;
if(!timerIsRunning){
// When the function is first called, it puts an onmouseup handler on the whole document
// that stops the process when the mouse is released. This is important if the user moves
// the cursor off of the button.
document.onmouseup = function(){
clearTimeout(holdTimer);
document.onmouseup = null;
timerIsRunning = false;
delay = initialDelay;
}
timerIsRunning = true;
}
}
button.onmousedown = changeValue;
}
//should only be called after the window/DOM has been loaded
window.onload = function() {
makeButtonIncrement(document.getElementById('btnUP'), "add", document.getElementById('amount'), 500, 0.7);
makeButtonIncrement(document.getElementById('btnDOWN'), "subtract", document.getElementById('amount'), 500, 0.7);
}
Это довольно быстро и грязно, но это должно дать Вам запуск. В основном Вы хотите настроить несколько начальных "констант", с которыми можно играть получить желаемое поведение. Начальное время между инкрементами составляет 1 000 мс, и на каждом повторении, если становятся 90% из того (1000, 990, 891... 100) и остановки, становящиеся меньшими на уровне 100 мс. Можно настроить этот фактор для получения более быстрого или более медленного ускорения. Остальное, которому я верю, достаточно близко к тому, что я думаю, что Вы шли для. Кажется, что Вы просто пропускали присвоения события. В window.onload
Вы будете видеть, что я присваиваюсь onmouseup
, и onmousedown
события к функциям, которые просто звонят increment()
или decrement()
функции с Вашим начальным тайм-аутом, или ClearTimeout()
функционируйте для остановки счетчика.
Править: Я изменил это немного для исправления ошибки. Теперь, если Вы переместите свой указатель мыши от кнопки и выпустите его, то остановит счетчик.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title><!-- Insert your title here --></title>
<script>
// Fake Constants
var INITIAL_TIME = 1000;
var ACCELERATION = .9;
var MIN_TIME = 100;
// create global variables to hold DOM objects, and timer
var up = null,
down = null,
count = null,
timer = null;
// Increment the counter
function increment (time) {
// decrease timeout by our acceleration factor, unless it's at the minimum
time = (time * ACCELERATION > MIN_TIME) ? (time * ACCELERATION) : MIN_TIME;
count.value ++ ;
// set the timeout for the next round, and pass in the new smaller timeout
timer = setTimeout(
function () {
increment(time);
}, time);
}
// Same as increment only subtracts one instead of adding.
// -- could easily make one function and pass an pos/neg factor instead
function decrement (time) {
time = time * ACCELERATION > MIN_TIME ? (time * ACCELERATION) : MIN_TIME;
count.value --;
timer = setTimeout(
function () {
decrement(time);
}, time);
}
// Initialize the page after all the forms load
window.onload = function () {
// initialization function
// assign DOM objects to our vars for ease of use.
up = document.getElementById('up_btn');
down = document.getElementById('dwn_btn');
count = document.getElementById('count');
// create event handlers for mouse up and down
up.onmousedown = function () {
increment(INITIAL_TIME);
}
down.onmousedown = function () {
decrement(INITIAL_TIME);
}
document.onmouseup = function () {
clearTimeout(timer);
}
}
</script>
</head>
<body>
<!-- Insert your content here -->
<form name="the_form">
<input type="button" value="Up" id="up_btn" /><br />
<input type="button" value="Down" id="dwn_btn" /></br>
<br />
Count:
<input type="text" value="0" id="count" />
</form>
</body>
</html>
Один аспект, который не будет пропущен, - то, что Вы сцепляетесь в onclick событие - который происходит при полном щелчке (Кнопка мыши вниз, и настроите). Это кажется, что Вы хотели бы прислушаться к другому отличному событию, http://www.w3schools.com/jsref/jsref_onmousedown.asp'> onMouseDown. Я думаю, необходимо ли было затем реализовать некоторые из других основанных на таймере решений, уже, учитывая Вас получил бы функциональность, которую Вы просите.
Удачи!
Самый легкий метод должен был бы просто добавить идентификатор к каждой из кнопок, затем использовать их, чтобы получить элементы и добавить события.
//should only be called after the window/DOM has been loaded
window.onload = function() {
//the buttons
var btnUP = document.getElementById('btnUP');
var btnDOWN = document.getElementById('btnDOWN');
//the amount
var amount = document.getElementById('amount');
//actions to occur onclick
var upClick = function() {
amount.value++;
}
var downClick = function() {
amount.value--;
}
//assign the actions here
holdit(btnUP, upClick, 1000, 2);
holdit(btnDOWN, downClick, 1000, 2);
}
<form>
<input type=button value="UP" class="btn" id='btnUP'>
<br />
<input type=text name=amount value=5 class="text" id='amount'>
<br />
<input type=button value="DOWN" class="btn" id='btnDOWN'>
</form>