资讯专栏INFORMATION COLUMN

为什么不用setInterval

EastWoodYang / 2481人阅读

Recently, I came across a requirement where I had to call a function repeatedly after specific time interval, like sending ajax call at every 10 seconds. Sure, best option seems as setInterval, but it blew up my face like a cracker :)

In order to understand why setInterval is evil we need to keep in mind a fact that javascript is essentially single threaded, meaning it will not perform more than one operation at a time.

In cases when functions takes longer than delay mentioned in setInterval (like ajax call, which might it prevent from completing on time), we will find that either functions have no breathing room or setInterval breaks it"s rhythm.

    var fakeCallToServer = function() {
        setTimeout(function() {
            console.log("returning from server", new Date().toLocaleTimeString());
        }, 4000);
    }



    setInterval(function(){ 

        let insideSetInterval = new Date().toLocaleTimeString();

        console.log("insideSetInterval", insideSetInterval);

        fakeCallToServer();
    }, 2000);

//insideSetInterval 14:13:47
//insideSetInterval 14:13:49
//insideSetInterval 14:13:51
//returning from server 14:13:51
//insideSetInterval 14:13:53
//returning from server 14:13:53 
//insideSetInterval 14:13:55
//returning from server 14:13:55

Try above code snippets in your console

As you can see from printed console.log statement that setInterval keeps on sending ajax calls relentlessly without caring previous call has returned or not.
This can queue up a lot of requests at once on the server.

Now, let"s try a synchronous operation in setInterval:

var counter = 0;

var fakeTimeIntensiveOperation = function() {

    for(var i =0; i< 50000000; i++) {
        document.getElementById("random");
    }

    let insideTimeTakingFunction  = new Date().toLocaleTimeString();

    console.log("insideTimeTakingFunction", insideTimeTakingFunction);
}



var timer = setInterval(function(){ 

    let insideSetInterval = new Date().toLocaleTimeString();

    console.log("insideSetInterval", insideSetInterval);

    counter++;
    if(counter == 1){
        fakeTimeIntensiveOperation();
    }

    if (counter >= 5) {
       clearInterval(timer);
    }
}, 1000);

//insideSetInterval 13:50:53
//insideTimeTakingFunction 13:50:55
//insideSetInterval 13:50:55 <---- not called after 1s
//insideSetInterval 13:50:56
//insideSetInterval 13:50:57
//insideSetInterval 13:50:58

We see here when setInterval encounters time intensive operation, it does either of two things, a) try to get on track or b) create new rhythm. Here on chrome it creates a new rhythm.

Conclusion
In case of asynchronous operations, setTimeInterval will create long queue of requests which will be very counterproductive.
In case of time intensive synchronous operations, setTimeInterval may break the rhythm.
Also, if any error occurs in setInterval code block, it will not stop execution but keeps on running faulty code. Not to mention they need a clearInterval function to stop it.
Alternatively, you can use setTimeout recursively in case of time sensitive operations.

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/106524.html

相关文章

  • 对于“不用setInterval,用setTimeout”的理解

    摘要:按照定时器的时间间隔,处第二个函数加入到事件队列,但此时正在执行,所以只能等待。这样做的好处是,在前一个定时器代码执行完之前,不会向队列插入新的定时器代码,确保不会有任何缺失的间隔。 JavaScript高级程序设计(第三版)(以下简称红宝书)22.3高级定时器中详细介绍了定时器setTimeout和setInterval,看完书后,深入理解了二者的区别,结合前辈们给我的建议用setT...

    impig33 评论0 收藏0
  • 通过 React Hooks 声明式地使用 setInterval

    摘要:但我认为谈不上的毛病,而是编程模型和之间的一种模式差异。相比类,更贴近编程模型,使得这种差异更加突出。声明本文采用循序渐进的示例来解释问题。本文假设读者已经使用超过一个小时。这是通过组件生命周期上绑定与的组合完成的。 本文由云+社区发表作者:Dan Abramov 接触 React Hooks 一定时间的你,也许会碰到一个神奇的问题: setInterval 用起来没你想的简单。 R...

    NoraXie 评论0 收藏0
  • [Javascript] 实现setInterval函数

    摘要:更方便的在于,由于自带定时器功能,我们甚至不用自己去维护一个时间戳。请注意这里由于没有调用另一个脚本,我们通过和的方式将我们的定时器程序传入中。 问题 经常使用Javascript的同学一定对setInterval非常熟悉,当使用setInterval(callback, timer)时,每经过timer毫秒时间,系统都将调用一次callback。请问全局如果没有提供setInterv...

    zhangwang 评论0 收藏0
  • 关于 setTimeout 与 setInterval,你需要知道的一切

    摘要:这里是结论,将是更惊艳的那一个。浏览器隔一段时间像服务器发送一个请求,询问这里有没有需要更新的消息。在响应回来时,才会继续发出第二个请求。但是,显然的,这对我们要做的事来说并不算是什么问题。 我们都知道的是setTimout是用来延迟一个简单的动作的,然而,setInterval的目的是用来重复执行某个动作的。 然后,以上只是一半的事实。因为如果一个函数需要在一个间隔时间内重复的执行,...

    rottengeek 评论0 收藏0
  • 前端碎语(3)

    摘要:而写成还可以满足你获得回调函数返回值的需求。而构建函数表达式的方法也不止把声明括起来这种,一些其他的操作符也可以,比如赋值号到目前为止,我们似乎能够得出结论函数声明后不可直接跟圆括号,而函数表达式后面可以。 使用setTimeout替代setInterval setInterval()这个间歇调用函数是应用得比较广的,尤其在比较古老的浏览器中实现动画效果时,往往离不开它。然而这个函数却...

    Brenner 评论0 收藏0

发表评论

0条评论

EastWoodYang

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<