简体   繁体   English

Javascript中的window.setInterval不要多次运行一个函数

[英]window.setInterval in Javascript do not run a function more than once

I want to update a partial view every 5000 ms (for example). 我想每5000毫秒更新一次局部视图(例如)。

I used bellow code to do it: 我使用下面的代码来做到这一点:

window.setInterval(function () {
    $.get("/Features/ShowDateTime").then(function (r) {
        $('#divDateTime').html(r);
    });
}, 5000)

This function run every 5000 ms truly (examined by using debugger command in the inner function) but ShowDateTime action run once (examined by using break-point in the action in its controller). 该函数真正每隔5000毫秒运行一次(通过内部函数中的debugger命令检查),但ShowDateTime操作运行一次(通过在其控制器中的动作中使用断点检查)。

So, what is the problem? 那么,有什么问题呢?

Assuming the code itself is working, it is likely you are getting cached data back on subsequent calls. 假设代码本身可以正常工作,则很可能在后续调用中获得了缓存的数据。 You need to cache-bust your calls. 您需要缓存呼叫。 An easy way is to simply append the current timestamp to the end of the URL: 一种简单的方法是将当前时间戳附加到URL的末尾:

window.setInterval(function () {
    $.get("/Features/ShowDateTime?" + Date.now()).then(function (r) {
        $('#divDateTime').html(r);
    });
}, 5000)

This will cause your browser to think it is a different URL each time so it won't cache and return the same result. 这会使您的浏览器每次都认为它是一个不同的URL,因此它不会缓存并返回相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM