2015-09-04 2 views
0

У меня есть сценарий, который предназначен для таймера. Я не уверен, как создать кнопку запуска. Сейчас он начинается сразу после загрузки страницы. Также кнопка паузы не работает.Таймер запуска и паузы

Вот скрипку я создал для него ...

https://jsfiddle.net/c6nqt9uy/

Тогда есть в любом случае для вывода текста после того, как таймер истек, как:

Время истекло!

По какой-то причине скрипт не показывает кнопку возобновления при нажатии паузы, но кнопка паузы ничего не делает.

function stopwatch(btn) { 
    if (btn.value == "Pause") { 
     clearInterval(ticker); 
     btn.value = "Resume"; 
    } else { 
+0

что это выпадающее меню? –

+0

Чтобы использовать более одного раза. – Ralph

+0

Итак, теперь вы хотите кнопку, которая запускает и останавливает таймер? –

ответ

0

Вы можете сделать это:

<button onClick="StartTimer()">Start</button> 

function StartTimer() { 
    //your code here 
} 
+0

Это не сработало. Спасибо за попытку! – Ralph

0

код, кажется, не будет вести себя должным образом на jsfiddle, так что я скачал его на моей локальной машине. Я обнаружил, что работает таймер, кнопка паузы/возобновления работает.

изменения я сделал:

  1. я удалил OnChange событие из отборного тега
  2. Я изменил значение кнопки «Пуск»
  3. я изменил функцию секундомера() это:

    function stopwatch(btn){ 
        if (btn.value == "Start"){ 
         start(); 
         btn.value = "Pause"; 
        } 
        else if (btn.value == "Pause"){ 
         clearInterval(ticker); 
         btn.value = "Resume"; 
        } 
        else { 
         ticker = setInterval(tick,1000); 
         btn.value = "Pause"; 
        } 
    } 
    

это то, что вы ищете?

+1

Создайте скрипт, чтобы показать, как это работает. – Bugfixer

+0

Я заметил, что совершил ошибку. Я забыл включить jquery. Теперь я это сделал. Вот скрипка. https://jsfiddle.net/czav0Leg/1/ Выберите значение из раскрывающегося списка и нажмите «Пуск» –

+0

PS. Для отображения таймера есть два места. #timer & #countdown. Я не знаю почему. Мой код влияет только на #countdown. –

0

var timeInSecs; 
 
var ticker; 
 
var start_time; 
 
function Countdown(start) { 
 
    this.start_time = start === undefined ? "1:00" : start ; 
 
    this.target_id = "#timer"; 
 
    this.name = "timer"; 
 
    start_time = this.start_time; 
 
} 
 

 
Countdown.prototype.init = function() { 
 
    this.reset(); 
 
    ticker = setInterval(this.name + '.tick()', 1000); 
 
} 
 

 
Countdown.prototype.reset = function() { 
 
    time = this.start_time.split(":"); 
 
    this.minutes = parseInt(time[0]); 
 
    this.seconds = parseInt(time[1]); 
 
    this.update_target(); 
 
} 
 

 
Countdown.prototype.tick = function() { 
 
    if (this.seconds > 0 || this.minutes > 0) { 
 
     if (this.seconds == 0) { 
 
      this.minutes = this.minutes - 1; 
 
      this.seconds = 59 
 
     } else { 
 
      this.seconds = this.seconds - 1; 
 
     } 
 
    } 
 
    this.update_target() 
 
} 
 

 
Countdown.prototype.update_target = function() { 
 
    seconds = this.seconds; 
 
    if (seconds < 10) seconds = "0" + seconds; 
 
    $(this.target_id).val(this.minutes + ":" + seconds) 
 
} 
 

 

 
var timer = new Countdown(); 
 
timer.init(); 
 

 

 
function start() { 
 
    var s = document.getElementById("period").value; 
 
    document.getElementById("period").disabled = true; 
 
    startTimer(s); 
 
} 
 

 
function startTimer(secs) { 
 
    timeInSecs = parseInt(secs); 
 
    document.getElementById("countdown").style.color = "black"; 
 
    clearInterval(ticker); 
 

 
    ticker = setInterval("tick()", 1000); 
 
    tick(); // to start counter display right away 
 
} 
 

 
function tick() { 
 
    var secs = timeInSecs; 
 
    if (secs > 0) { 
 
     timeInSecs--; 
 
     showTime(secs); 
 
    } else { 
 
     timeInSecs--; 
 
     document.getElementById("countdown").style.color = "red"; 
 
     document.getElementById("countdown").innerHTML = "You have exceeded your time by " + (hhmmss(Math.abs(timeInSecs))); 
 
     document.getElementById("period").disabled = false; 
 
    } 
 
} 
 

 
function showTime(secs) { 
 
    var hours = Math.floor(secs/3600); 
 
    secs %= 3600; 
 
    var mins = Math.floor(secs/60); 
 
    secs %= 60; 
 
    var result = ((hours < 10) ? "0" : "") + hours + ":" + ((mins < 10) ? "0" : "") + mins + ":" + ((secs < 10) ? "0" : "") + secs; 
 
    document.getElementById("countdown").innerHTML = result; 
 
} 
 

 
function stopwatch(btn) { 
 
    if (btn.value == "Pause") { 
 
     clearInterval(ticker); 
 
     btn.value = "Resume"; 
 
    } else { 
 
     btn.value = "Pause" 
 
     var timer = new Countdown($('#timer').val()); 
 
     timer.init(); 
 
    } 
 
} 
 

 
function hhmmss(secs) { 
 
    var hrs = Math.floor(secs/3600); 
 
    var mns = Math.floor(secs/60) % 60; 
 
    secs = secs % 60; 
 
    if (hrs < 10) hrs = "0" + hrs; 
 
    if (mns < 10) mns = "0" + mns; 
 
    if (secs < 10) secs = "0" + secs; 
 
    return mns + " minutes " + secs + " seconds"; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<input type="text" id="timer"> 
 
<select id="period" onchange="start()"> 
 
    <option value="0">Select time required</option> 
 
    <option value="30">30 Seconds</option> 
 
    <option value="60">1 Minute</option> 
 
    <option value="300">5 Minutes</option> 
 
    <option value="900">15 minutes</option> 
 
    <option value="1800">30 minutes</option> 
 
    <option value="2700">45 minutes</option> 
 
    <option value="3600">60 minutes</option> 
 
    <option value="4500">75 minutes</option> 
 
    <option value="5400">90 minutes</option> 
 
    <option value="6300">105 minutes</option> 
 
    <option value="7200">120 minutes</option> 
 
</select> \t <span id="countdown" style="font-weight: bold;"></span> 
 
<br> 
 
<br> 
 
<input type="button" value="Pause" onclick="stopwatch(this);" />

+0

Кнопка паузы полностью останавливает таймер. Есть ли в любом случае, чтобы получить сообщение о времени? – Ralph

0

Пожалуйста, попробуйте это один сударь:

var timeInSecs; 
var ticker; 
var start_time; 
function Countdown(start) { 
    this.start_time = start === undefined ? "1:00" : start ; 
    this.target_id = "#timer"; 
    this.name = "timer"; 
    start_time = this.start_time; 
} 

Countdown.prototype.init = function() { 
    this.reset(); 
    ticker = setInterval(this.name + '.tick()', 1000); 
} 

Countdown.prototype.reset = function() { 
    time = this.start_time.split(":"); 
    this.minutes = parseInt(time[0]); 
    this.seconds = parseInt(time[1]); 
    this.update_target(); 
} 

Countdown.prototype.tick = function() { 
    if (this.seconds > 0 || this.minutes > 0) { 
     if (this.seconds == 0) { 
      this.minutes = this.minutes - 1; 
      this.seconds = 59 
     } else { 
      this.seconds = this.seconds - 1; 
     } 
    } 
    this.update_target() 
} 

Countdown.prototype.update_target = function() { 
    seconds = this.seconds; 
    if (seconds < 10) seconds = "0" + seconds; 
    $(this.target_id).val(this.minutes + ":" + seconds) 
} 


var timer = new Countdown(); 
timer.init(); 


function start() { 
    var s = document.getElementById("period").value; 
    document.getElementById("period").disabled = true; 
    startTimer(s); 
} 

function startTimer(secs) { 
    timeInSecs = parseInt(secs); 
    document.getElementById("countdown").style.color = "black"; 
    clearInterval(ticker); 

    ticker = setInterval("tick()", 1000); 
    tick(); // to start counter display right away 
} 

function tick() { 
    var secs = timeInSecs; 
    if (secs > 0) { 
     timeInSecs--; 
     showTime(secs); 
    } else { 
     timeInSecs--; 
     document.getElementById("countdown").style.color = "red"; 
     document.getElementById("countdown").innerHTML = "You have exceeded your time by " + (hhmmss(Math.abs(timeInSecs))); 
     document.getElementById("period").disabled = false; 
    } 
} 

function showTime(secs) { 
    var hours = Math.floor(secs/3600); 
    secs %= 3600; 
    var mins = Math.floor(secs/60); 
    secs %= 60; 
    var result = ((hours < 10) ? "0" : "") + hours + ":" + ((mins < 10) ? "0" : "") + mins + ":" + ((secs < 10) ? "0" : "") + secs; 
    document.getElementById("countdown").innerHTML = result; 
} 

function stopwatch(btn) { 
    if (btn.value == "Pause") { 
     clearInterval(ticker); 
     btn.value = "Resume"; 
    } else { 
     btn.value = "Pause" 
     var timer = new Countdown($('#timer').val()); 
     timer.init(); 
    } 
} 

function hhmmss(secs) { 
    var hrs = Math.floor(secs/3600); 
    var mns = Math.floor(secs/60) % 60; 
    secs = secs % 60; 
    if (hrs < 10) hrs = "0" + hrs; 
    if (mns < 10) mns = "0" + mns; 
    if (secs < 10) secs = "0" + secs; 
    return mns + " minutes " + secs + " seconds"; 
} 

DEMO

Я думаю, что будет лучше, если вы будете создавать часы объекта. См. Код (см. Демо: DEMO1)

Смежные вопросы