JavaScript - Foundation timer, callback function, countdown

Two timers provided by window

  • setTimeout()
  • setInterval()

window. SetTimeout (calling function, [number of milliseconds delayed]);

The setTimeout() method is used to set a timer. When the delay time is up, the calling function will be executed, and it will end only once.

<script>
         //The delay time is in milliseconds
        //setTimeout('callback()',2000); It is the same as the following, but it is not advocated
      setTimeout(callback,2000);
      function callback () {
          alert('Two seconds passed');
      }
         var timer1 = setTimeout(callback, 3000);
        var timer2 = setTimeout(callback, 5000);
     </script>

There may be multiple timers in the page. Generally, you should add an identifier (name) to the timer (such as timer1 and timer2)

The calling function setTimeout() is also called callback. Ordinary functions are called directly according to the code sequence, and this requires waiting time. It is called only when the time is up, so it is called a callback function. When the last thing is done, call this function again. Previously learned element ο Nclick = fund() {} or element addEventListener('click',fn); The function inside is also called callback function.

Case: ads that automatically close after five seconds

 <img src="images/ad.jpg" alt="" class="ad">
    <script>
        var ad = document.querySelector('.ad');
        setTimeout(function() {
            ad.style.display = 'none';
        }, 5000);
    </script>

Stop the setTimeout() timer

window.clearTimeout(timeout ID) / / window can be omitted

The clearTimeout() method cancels the timer previously established by calling setTimeout()

<button>Click stop timer</button>
    <script>
        var btn = document.querySelector('button');
        var timer = setTimeout(function() {
            console.log('It exploded');

        }, 5000);
        btn.addEventListener('click', function() {
            clearTimeout(timer);  //(identifier of the timer)
        })
    </script>

setInterval() timer

window. Setinterval (callback function, [interval]);

The rest is the same as setTimeout (), but the function of this timer is to call the function every other time.

Case: Countdown

  1. The countdown is constantly changing, so you need a timer to automatically change (setInterval)
  2. Previously, three boxes were set to store hours, minutes and seconds respectively
  3. The three boxes use innerHTML to put the calculated hours, minutes and seconds
  4. The first execution is also in milliseconds, so the refresh page will be blank
  5. By encapsulating the function, call this function once to prevent the page blank from being refreshed at the beginning
  window.addEventListener('load',function(){
        var hour = document.querySelector('.hour'); 
        var minute = document.querySelector('.minute'); 
        var second = document.querySelector('.second'); // second
        var inputTime = +new Date('2022-1-18 18:00:00'); // Returns the total number of milliseconds of the user input de deadline
        countDown();//Call in advance to prevent blank space from refreshing intervals for one second.
        //Turn on the timer
        setInterval(countDown,1000);

        function countDown() {
            var nowTime = +new Date(); // Returns the total number of milliseconds of the current time
            var times = inputTime>nowTime?(inputTime - nowTime) / 1000 : 0; // times is the total number of seconds remaining  
            var h = parseInt(times / 60 / 60 % 24); //Time
            h = h < 10 ? '0' + h : h;
            hour.innerHTML = h; // Give the remaining hours to the black box
            var m = parseInt(times / 60 % 60); // branch
            m = m < 10 ? '0' + m : m;
            minute.innerHTML = m;
            var s = parseInt(times % 60); // Current seconds
            s = s < 10 ? '0' + s : s;
            second.innerHTML = s;
        }
       })
     </script>
         <div>
            <span class="hour">1</span>
            <span class="minute">2</span>
            <span class="second">3</span>
        </div>

 

Stop setInterval() timer

The clearInterval () method cancels the timer previously established by calling setInterval (). The parameter is an identifier.

It is best to define the identifier of setInterval () as a global variable and assign a value.

<button class="begin">Turn on the timer</button>
    <button class="stop">Stop Timer </button>
    <script>
        var begin = document.querySelector('.begin');
        var stop = document.querySelector('.stop');
        var timer = null; // The global variable null is an empty object
        begin.addEventListener('click', function() {
            timer = setInterval(function() {
                console.log('ni hao ma');

            }, 1000);
        })
        stop.addEventListener('click', function() {
            clearInterval(timer);
        })
    </script>

Case: SMS sending case

  1. After the button is clicked, disabled will be disabled and set to true
  2. At the same time, the content in the button will change. Note that the content in the button is modified through innerHTML
  3. The number of seconds varies, so a timer is needed
  4. Define a variable that is decremented in the timer
  5. If the variable is 0, it means that the time is up, we need to stop the timer and restore the initial state of the button
   phone number: <input type="number"> <button>send out</button>
    <script>
        var btn = document.querySelector('button');
        var time = 60; // Define the number of seconds left
        btn.addEventListener('click', function() {
            btn.disabled = true;
            var timer = setInterval(function() {
                if (time == 0) {
                    // Clear timer and reset button
                    clearInterval(timer);
                    btn.disabled = false;
                    btn.innerHTML = 'send out';
                } else {
                    btn.innerHTML = 'Remaining' + time + 'second';
                    time--;
                }
            }, 1000);

        })
    </script>

 

Keywords: Javascript Front-end

Added by mikusan on Tue, 18 Jan 2022 10:48:21 +0200