程序笔记   发布时间:2022-07-12  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了定时器的运行和停止大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

运行定时器:当我们想手动开启定时器时࿰c;我们可以用一个函数来包装这个定时器࿰c;这样的话调用函数时就能开启定时器࿰c;例如:

function time() {

                  seTinterval(function(){

                  alert('定时器开启成功')

           }, 2000)

        }             //将定时器写进函数。

        time();    //调用函数。

结束定时器:当我们想停止定时器时࿰c;可以对定时器本身进行命名࿰c;并运用clearInterval函数来结束定时器的运作。

var t = seTinterval(function () {

    alert('定时器开启成功')

}, 2000)              //用t来对定时器进行命名
clearInterval(t);     //消除名字为t的这个定时器

接下来是一个完整案例࿰c;分别运用两个button按钮来控制一个div盒子的运行和停止


<!DOCTYPE html>
<html lang="zh=CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            top: 250px;
            left: 300px;
            height: 100px;
            width: 100px;
            border: 2px solid black;
            border-radius: 10px;
        }
        button {
            height: 30px;
            width: 60px;
            position: absolute;
            top: 200px;
            left: 290px;
        }
        button.stop {
            position: absolute;
            top: 200px;
            left: 360px;
        }
    </style>
</head>
<body>
    <button class="right">往右</button>
    <button class="stop">停止</button>
    <div>
    </div>
    <script>
        var div = document.querySELEctor('div');
        var btn = document.querySELEctor('button.right');
        var stop = document.querySELEctor('button.stop');
        var showtime = function () {
            div.style.left = div.offsetLeft + 1 + 'px';
        }
        var t;
        function time() {
            t = seTinterval(showtime, 20)
        }
        btn.addEventListener('click', function () {
				clearInterval(t);
            time();
        })
        stop.addEventListener('click', function () {
            clearInterval(t);
        })
    </script>
</body>
</html>

谢谢大家。

大佬总结

以上是大佬教程为你收集整理的定时器的运行和停止全部内容,希望文章能够帮你解决定时器的运行和停止所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。