我希望我的 ajax 调用运行时间不超过 200 毫秒,所以我写道
if (update_timer != null) {
// do nothing
} else {
// update_timer == null
update_timer = setTimeout (function () {perform_ajax_refresh()}, 200);
}
在perform_ajax_refresh()函数中做了:
function perform_ajax_refresh()
{
clearTimeout(update_timer);
console.log(update_timer);
// do ajax here
}
这两行是我杀死 update_timer 变量的努力。正确的做法是什么???我猜想clearTimeout没有任何意义,但这是我将update_timer
变量设置为null的努力。
最佳答案
Javascript 是按值传递的,因此 clearTimeout
不可能修改作为参数传递的变量。
您的担忧是合理的,解决问题的最简单方法是在 clearTimeout(update_timer)
之后立即设置 update_timer = null
。
(另外,请避免以这种方式使用全局变量。完成此操作后,请尝试重写代码,以便多个此类模块可以同时存在于一个网页上。)
关于javascript - js如何杀死定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21799879/