How to clear the timer in js

1. Setting the timer

The window object provides two methods to achieve the effect of the timer,

are window .setTimeout() and window.setInterval. The former can make a piece of code run after a specified time; the latter can make a piece of code run once every specified time. Their prototypes are as follows:

window.setTimeout(code,millisec);

 var i = 0  ; //Set the timer (loop to execute)
      var timeId = setInterval(function () {
       i++;
       console.log(&# 39; Scheduled operation: & # 39; + i + & # 39; times & # 39;)
       }, 500) //Clear timer
      my$('btn').Onclick= function () {
       window.clearInterval(timeId)
     }

window.setInterval(code,millisec);

var i = 0; //Set  Timer (one shot timer)
     var timeId = setTimeout(function () {
       i++;
       console.log(&# 39; Scheduled operation: & # 39; + i + & # 39; times & # 39;)
     }, 500) //Clean up the timer (although this timer is only once, it must be cleaned up, which can not only release the memory, but also facilitate the judgment of the following code.)
     my$('btn').Onclick= function () {
       window.clearTimeout(timeId)
     }

Among them, code can be a piece of code enclosed in quotation marks, or a function name. When the specified time is reached, the system will automatically call the function. When using the function name as the call handle, Cannot have any parameters;

When using a string, you can write the parameters to be passed in it. The second parameter in the two methods is millisec, which represents the number of milliseconds for delay or repeated execution.

Second, clear the timer

When the timer is called, it will return an integer number, which represents the serial number of the timer, that is, the first How many timers, so the timer is cleared with the help of this returned number.

Timer clear method: clearTimeout(obj) and clearInterval(obj). (Note that the corresponding clearing method is used for the corresponding timer)

The above is the detailed content of how to clear the timer in js. For more information, please pay attention to other related articles on 1024programmer.com!

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/how-to-clear-the-timer-in-js/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: 34331943@QQ.com

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索