Timers (setInterval and setTimeout)

1. Timer setInterval--------commonly used, repeated cycle

   < input type = "button" value = = "stop" id = "btn" > 
    < script > 
    // timer setInterval(parameter 1, parameter 2) 
    // parameter 1----->function 
    // parameter 2-- --->Event----unit milliseconds-----1000 milliseconds= 
    1 second The code that executes the function once.. 
    // The return value is the id of the timer 
    // Clear the timer with clearInterval(id) 
    var timeId = setInterval( function (){
     // Set a timer, and the console outputs "haha" for one second 
        console.log( " Haha " );
    },1000)
    document.getElementById( " btn " ).onclick = function (){
     // Click the button to stop the timer, the parameter is the id of the timer to be cleared 
        window.clearInterval(timeId);
    };
    </script>

Second, the timer setTimeout-------one-time

   < input type = "button" value = = "stop" id = "btn" > 
    < script > 
        // timer setTimeout(parameter 1, parameter 2) 
        // parameter 1----->function 
        // parameter 2-- --->Event----unit milliseconds-----1000 
        milliseconds = 1 
        second It is the id of the timer 
        // ClearTimeout is used to clear the timer----although it is a one-time timer, it should be cleaned up, otherwise it will always occupy the memory 
        var timeId = setTimeout( function () {
             // Set a timer, One second console output "haha" 
            console.log( " haha " );
        }, 1000)
        document.getElementById( " btn " ).onclick =  function () {
             // Click the button to stop the timer, the parameter is the id of the timer to be cleared 
            window.clearTimeout(timeId);
        };
    </script>

3. Case

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325365764&siteId=291194637
Recommended