14-----定时器

在js中的定时器分两种:1、setTimeout()    2、setInterval()

 

1、setTimeOut()

只在指定时间后执行一次

/定时器 异步运行  
function hello(){  
alert("hello");  
}  
//使用方法名字执行方法  
var t1 = window.setTimeout(hello,1000);  
var t2 = window.setTimeout("hello()",3000);//使用字符串执行方法  
window.clearTimeout(t1);//去掉定时器
//等待2秒之后 fn会去执行 fn我们称为叫回调函数
        setTimeout(function() {
            // body...
            console.log(2222);
        }, 2000);

        console.log(1111);

 

2、setInterval()

 在指定时间为周期循环执行

/实时刷新  时间单位为毫秒  
setInterval('refreshQuery()',8000);   
/* 刷新查询 */  
function refreshQuery(){  
  console.log('每8秒调一次') 
}

 

    var a = 0 ;
    setInterval(function(){
        a++;
        console.log(a);
    },300)   

 

刷盒子移动

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="box" style="width: 100px;height: 100px;background-color: red;">
</div>

<script>

    var a = 0 ;
    var oDiv = document.getElementById('box');
    setInterval(function(){
        a++;   //a+=3
        oDiv.style.marginLeft = a+'px';
        console.log(a)
    },300);    //每300毫秒
    
</script>
</body>
</html>
复制代码

 

清除定时器

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="box" style="width: 100px;height: 100px;background-color: red;">
</div>
    <button id="btn">停止</button>
<script>
        var a = 0;
        function $(id){
            return document.getElementById(id);
        }

        var c = setInterval(function() {
            // body...
            a+=3;
            $('box').style.marginLeft = a+'px';
            console.log(a);
        },50);

        $('btn').onclick = function(){
            clearInterval(c);
        };

//
//        //等待2秒之后 fn会去执行 fn我们称为叫回调函数
//        setTimeout(function() {
//            // body...
//            console.log(2222);
//        }, 2000);
//
//        console.log(1111);

</script>
</body>
</html>
复制代码

 

两种方法根据不同的场景和业务需求择而取之,

对于这两个方法,需要注意的是如果要求在每隔一个固定的时间间隔后就精确地执行某动作,那么最好使用setInterval,而如果不想由于连续调用产生互相干扰的问题,尤其是每次函数的调用需要繁重的计算以及很长的处理时间,那么最好使用setTimeout

 

posted @   王竹笙  阅读(126)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示