Home  >  Article  >  Web Front-end  >  How to clear timer in es6

How to clear timer in es6

青灯夜游
青灯夜游Original
2022-04-13 15:12:157266browse

Two methods: 1. Use clearTimeout() to clear the setTimeout timer, the syntax "clearTimeout (timer return value)"; 2. clearInterval() to clear the setInterval timer, the syntax "clearInterval (return value)" .

How to clear timer in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Two timers for JS

window.setTimeout([function],[interval])

Set a timer and set a waiting time. When the time is reached, the corresponding method is executed. When the method execution is completed, the timer stops.

window.setInterval([function],[interval])

Set a timer and set a waiting time. When the time is reached, execute corresponding method.

When the method execution is completed, the timer does not stop. The corresponding method will be re-executed every so long in the future until we manually clear the timer.

Note: setTimeout() only executes code once. If you want to call it multiple times, use setInterval() or have the code itself call setTimeout() again.

Timer return value

The timer in JS has a return value. The return value is a number, representing the current timer.

var timer1=window.setTimeout(function(){},1000);  //timer1->1 当前是第一个定时器
var timer2=window.setTimeout(function(){},1000);  //timer2->2` 当前是第二个定时器
var timer3=window.setTimeout(function(){},1000);   //timer3->3 当前是第三个定时器

It should be noted that even if the timer is cleared, its return value will not be cleared, and the return value of the timer set later will continue to be queued based on its return value.

How to clear the timer

If the timer is not cleared in time, there may be a risk of memory overflow. So when we use timers, we need to consider clearing them at the appropriate time.

The clear timer has two functions:

  • The destruction function of setTimeout is clearTimeout

  • The destruction function of setInterval is clearInterval

setInterval object or setTimeout object, these two timer objects will only be recycled from the stack space when the window object is destroyed. You cannot notify the garbage collection machine to automatically recycle by changing the pointer of the variable to point to null. If you intend to destroy the setInterval object in the stack memory of the window object before the window object is closed, you can only destroy it through clearInterval

clearTimeout(id_of_settimeout)

Definition: Block/cancel the scheduled execution function set by the setTimeout() method.

Parameters: id_of_settimeout is the ID value returned when calling the setTimeout() function. Using the return identifier as a parameter can cancel the scheduled execution operation set by the setTimeout().

Note: To use the clearTimeout(id_of_setinterval) method, use global variables when creating and executing scheduled operations:

var myVar = setTimeout(function(){ alert("Hello"); }, 3000);
clearTimeout(myVar);
  • Do you need to clear setTimeOut in time

function testTimeout () {
	console.log('1111')
	console.log(setTimeout(testTimeout, 3000));
}

The above code calls testTimeout recursively, but setTimeout will always generate setTimeout objects; although it will be recycled by GC, the time is uncertain. This is more dangerous and may cause memory overflow.

So we should call clearTimeout before each setTimeout to prevent setTimeout objects from being continuously created and not recycled by GC.

var timeHandle = null;
function testTimeout () {
    if (timeHandle) {
    	// 调用之前,先清理,防止一直生成对象
    	// ps. setInterval 定时器也应该按这种模式处理
    	clearTimeout(timeHandle);
        timeHandle = null;
    }
	console.log('1111');
	console.log(timeHandle = setTimeout(testTimeout, 3000));
}

clearInterval(id_of_setinterval)

Definition: Can cancel/stop the scheduled execution operation set by the setInterval() function.

Parameters: id_of_setinterval is the ID value returned when calling the setInterval() function. Only by using the return identifier as a parameter can the scheduled execution operation set by setInterval() be cancelled.

Note: To use the clearInterval() method, use global variables when creating and executing scheduled operations:

var myVar = setInterval(function(){ myTimer() }, 1000);
clearInterval(myVar);
  • Do you need to clear setInterval in time

function testInterval () {
	console.log('1111')
	console.log(setInterval(testInterval, 3000));
}

The above code calls testInterval recursively, but setInterval will always generate setInterval objects; although it will be recycled by GC, the time is uncertain. This is more dangerous and may cause memory overflow.

So we should call clearInterval before each setInterval to prevent setInterval objects from being continuously created and not recycled by GC.

var timeHandle = null;
function testInterval () {
    if (timeHandle) {
    	// 调用之前,先清理,防止一直生成对象
    	clearInterval(timeHandle);
        timeHandle = null;
    }
	console.log('1111');
	console.log(timeHandle = setInterval(testInterval, 3000));
}

Extended knowledge: Use setTimeout to simulate setInterval behavior

Normally: using setTimeOut() recursively, the effect is equivalent to using setInterval()

Benefits:

  • Simplify the code

  • Ensure the accuracy of the function calling sequence of the asynchronous queue. The setInterval defect will lead to a large amount of data. Sometimes, the execution order of function calls in the asynchronous queue is out of order. For example, before the execution of this function is finished, the next one starts to be executed, but not with recursion. Recursion means that the next entity of the function is recursively created in the stack space and called after the current function is executed.

//实现的方法挺简单的 ,如下代码
//参数: 毫秒  需要执行的方法
function console1() {
    console.log(111);
    if(timer){
        clearTimeout(timer);
    }
    timer = setTimeout(function(){
        console1();
    }, 3000);
}
console1()

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of How to clear timer in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn