Search code examples
javascriptbuttontimercountdown

how can activate my countdown timer with button?


I have a countdown timer function writed in javascript.Its working but it starts when i start the page.I want it should be start when the button clicked.

  function startTimer(duration, display) {
        var timer = duration, minutes, seconds;
        setInterval(function () {

            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display.text(minutes + ":" + seconds);

            if (--timer < 0) {
              //  timer = 0;

                time.style.display = "none";
                time2.style.display2 = "none";
                redxsms.style.display = "none";
                onaysms.style.display = "none";
                tekraruyarionay.style.display = "block";
                tekraruyarired.style.display = "block";

                // time.style.display="block";
                setTimeout(function () { location.reload() }, 5000);
            }
        }, 1000);
    }



   jQuery(function ($) {
        var fiveMinutes = 60 * 3,
            display = $('#time');
        display2 = $('#time2');
        startTimer(fiveMinutes, display);
        startTimer(fiveMinutes, display2);

    });

this is the countdown function.

  <button class="ui toggle button" onclick="      hideshow(document.getElementById('onaysms')); show(this);" id="onaytoggle">

this is button when i click it should activate.

<span id="time"></span>

It starts when the page start how can i start when the button clicked?


Solution

  • Insert your timer call in an "onclick" event like this, it will be fired when you click on the button.

    If you have several buttons on your page, i would advise you to give one an id by adding this in your html : id='timerToggle' and then replacing the $("button.toggle") in the code below by $("#timerToggle")

     jQuery(function ($) {
               $("button.toggle").click(function(){
                   var fiveMinutes = 60 * 3,
                       display = $('#time');
                   display2 = $('#time2');
                   startTimer(fiveMinutes, display);
                   startTimer(fiveMinutes, display2);
               });
            });