Home  >  Article  >  Web Front-end  >  How to stop settimeout in jquery

How to stop settimeout in jquery

WBOY
WBOYOriginal
2022-04-24 17:58:074135browse

In jquery, you can use the clearTimeout() method to stop settimeout. This method is used to cancel the timeout set by the setTimeout() method. The parameter must be the ID value returned by setTimeout(). The syntax is "clearTimeout(ID value )".

How to stop settimeout in jquery

The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.

How to stop settimeout in jquery

The clearTimeout() method can cancel the scheduled operation set by the setTimeout() method.

Cancel the timeout set by the setTimeout() method

The parameter of the clearTimeout() method must be the ID value returned by setTimeout().

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

myVar = setTimeout("javascript function", milliseconds);

If the method has not been executed, we can use clearTimeout() to prevent it.

clearTimeout(id_of_settimeout)

id_of_setinterval is the return value obtained when calling the setTimeout() function. Using the return identifier as a parameter can cancel the scheduled execution operation set by the setTimeout().

The example is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>123</title>
</head>
<body>
<p>点击按钮,等待 3 秒后弹出 "Hello" 。</p>
<p>点击第二个按钮来阻止弹出函数 myFunction 的执行。 (你必须在 3 秒前点击)</p>
<button onclick="myFunction()">先点我</button>
<button onclick="myStopFunction()">阻止弹出</button>
<script>
var myVar;
function myFunction() {
    myVar = setTimeout(function(){ alert("Hello") }, 3000);
}
function myStopFunction() {
    clearTimeout(myVar);
}
</script>
</body>
</html>

Output result:

How to stop settimeout in jquery

If you only click the first button, three seconds A pop-up window will appear:

How to stop settimeout in jquery

If the second button is clicked within three seconds after clicking the first button, the pop-up window will not appear.

Recommended related video tutorials: jQuery video tutorial

The above is the detailed content of How to stop settimeout in jquery. 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