javascript - 清除javascript或angular中的轮询超时

标签 javascript angularjs polling

function scan (id) {    
    $http({
            method: "POST",
            url:( "url"),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            data: $.param({id: id}),
        })
            .then(scanComplete)
            .catch(function(message) {
                throw new Error("XHR Failed ",message);
            });

        function scanComplete(response, status, headers, config) {
            //do something , show errors, popup , call to other functions
        }
  setTimeout(function() {scan())}, 1000);
}

这是我轮询的功能,例如检查数据库中是否有新通知。

我根本没有清除超时,也​​不使用 $timeout 。是不是错了?是否会导致 chrome 问题,如卡住或 CPU 开销?

我怎样才能清除,我怎样才能检查我是否真的清除了它

所有功能和用户界面方面。来自没有 Controller 的 Angular 服务/工厂(除了服务调用)

最佳答案

只需要在scanComplete函数中再次调用

function scanComplete(response, status, headers, config) {
    //do something , show errors, popup , call to other functions
    setTimeout( scan, 1000); //invoke after your ajax is complete
}

这将确保您在任何给定时间点仅触发一次扫描

I don't clear the timeout at all and don't use the $timeout . is it mistake ? is it cause to chrome problem like freezing or CPU overhead?

由于您在任何时间点都只触发一次扫描,而且在第一个扫描完成后也是如此,我看不出这将如何产生任何 CPU 开销。

关于javascript - 清除javascript或angular中的轮询超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47976066/

相关文章:

javascript - JavaScript/Jquery 中句子的第一个字母大写

javascript - 为什么 nextImg 和 prevImg 不能设置元素的 src 属性?

Javascript:如何隐藏动态创建的div?

javascript - ionic 框架 - 输入输入时 Android 中的屏幕闪烁

angularjs - angular2 中的 package.json 是否需要以任何方式启动应用程序?

php - 使用 php 监视 mysql 更改 **WITHOUT** 轮询

ajax - Grails通过ajax调用轮询服务器

javascript - navigator.mediaDevices.getDisplayMedia 不支持

javascript - 从服务器 Angular 加载数据并在单独的页面上显示信息

java - 如何实现异步处理