[英]javascript/jquery clearInterval works but with delay
I have a flask-environment running server-sided, which calculates the distance between it's current position (GPS-Module attached to the server) and given coordinates.我有一个运行服务器端的烧瓶环境,它计算当前 position(连接到服务器的 GPS 模块)和给定坐标之间的距离。 I want a text to update when a certain event occurs.
我希望在发生特定事件时更新文本。 It should keep updating until a different event occurs.
它应该不断更新,直到发生不同的事件。
This is my function to update the distance:这是我的 function 更新距离:
function getDistToCurPos(lat, lon) {
$.getJSON('/getDistFromCurPosToPoint', {
pLat: lat,
pLon: lon,
},
function(data){
dist = data;
let distStr = String(dist);
let outStr = '<div class="distanceOutput"> Distance: '.concat(distStr).concat("</div>");
$( "div.distanceOutput" ).replaceWith( outStr );
});
};
When the start-event occurs, I call the function as follows (with example-values 38 and 9):当开始事件发生时,我调用 function 如下(示例值 38 和 9):
distRefreshID = setInterval(function() { getDistToCurPos(38,9); }, distUpdateTime);
distUpdateTime
is set to 500. The server response takes 15 ms in average. distUpdateTime
设置为 500。服务器响应平均需要 15 毫秒。
Initial state of the text:文字的初始state:
<div class="distanceOutput">Inactive !</div>
To terminate updating the text, I call the following, when a different event occurs:为了终止更新文本,当发生不同的事件时,我调用以下命令:
if ( distRefreshID !== 0) {
clearInterval(distRefreshID);
$( "div.distanceOutput" ).replaceWith('<div class="distanceOutput">Inactive again!</div>');
distRefreshID = 0;
}
The code works in general.该代码通常有效。 But when the stop-event occurs, I see "Inactive again."
但是当停止事件发生时,我看到“再次处于非活动状态”。 only for a short moment, After that.
只是片刻,之后。 the text keeps getting updated with the current values for a few seconds.
文本会在几秒钟内使用当前值不断更新。
Any tips, where my bug is?任何提示,我的错误在哪里?
setInterval does not initially call the function, it calls it after
x milliseconds have passed so if you want to instantly update the content call the function right before setting the interval setInterval 最初不会调用 function,它会在 x 毫秒
after
调用它,因此如果您想立即更新内容,请在设置间隔之前调用 function
getDistToCurPos(38,9);
distRefreshID = setInterval(function() { getDistToCurPos(38,9); }, distUpdateTime);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.