JS函数在被再次调用时开始在更短的时间内执行

JS function started to execute in lesser time when it is called again

本文关键字:执行 开始 时间 函数 调用 JS      更新时间:2023-09-26

我需要在一段时间间隔后连续调用一个函数,所以我遵循了这个链接提供的解决方案。

下面是JS代码。

    function displayLiveLocation()
    {
        var location = new Array();
        var currentcord = new Array();
        $('input[type=checkbox][name="IMSeries[]"]:checked').each(function() {
           location.push($(this).val()); 
           var current = $(this).val();
           currentcord.push($('#'+current+'_H').val());
        }); 
        copyofAutotrack(currentcord , location);
        setTimeout(function() {
            display();
        }, 15000);
    }

这是HTML代码

   <div class="checkbox"> 
    <input type="checkbox" onclick="displayLiveLocation()" value="0358911020092058" name="IMEISeries[]" class="IMEISeriesClass[]">       
    <input type="hidden" value="26.79997253418,75.799194335938" id="0358911020092058_H"> 
   </div>

有多个复选框和隐藏字段,其唯一id类似于上面的一个。当单击复选框时,相应的函数开始以15秒的间隔执行。但是,当单击另一个复选框时,也会发生同样的事情,使该函数以更短的时间间隔执行,因为对函数进行了另一次调用。我希望这个函数只在15秒内执行。任何帮助都会很感激。提前谢谢。

我不知道如何在这个网站上搜索这个,所以我问了这个问题。

当您在第一次超时执行之前再次单击复选框时,第一次单击的超时将在第一次单击后15秒发生,但使用第二次单击的数据。

如果你想让它们用自己的数据集分别发生,你可以在调用时将数据发送到函数中,而不是让它使用当前数据:

function displayLiveLocation()
{
    var location = new Array();
    var currentcord = new Array();
    $('input[type=checkbox][name="IMSeries[]"]:checked').each(function() {
       location.push($(this).val()); 
       var current = $(this).val();
       currentcord.push($('#'+current+'_H').val());
    }); 
    copyofAutotrack(currentcord, location);
    setTimeout(function() {
        display(currentcord, location);
    }, 15000);
}

如果您想完全停止第一个超时,只等待第二个超时,您可以使用clearTimeout:

var displayTimeout = null;
function displayLiveLocation()
{
    var location = new Array();
    var currentcord = new Array();
    $('input[type=checkbox][name="IMSeries[]"]:checked').each(function() {
       location.push($(this).val()); 
       var current = $(this).val();
       currentcord.push($('#'+current+'_H').val());
    }); 
    copyofAutotrack();
    if (displayTimeout != null) {
      clearTimeout(displayTimeout);
    }
    displayTimeout = setTimeout(function() {
        displayTimeout = null;
        display(currentcord, location);
    }, 15000);
}

每次单击复选框时,都会启动一个新的超时。如果用户在几秒钟内单击了3个复选框,则调用3个超时,并在另一个之后不久运行。

一个解决方案是,在调用新的超时之前停止上一次超时,使用clearartimeout:

var timeoutActive = false; // status of the timeout
function displayLiveLocation()
{
    // your code
    window.clearTimeout(timeoutActive); // cancels the last timeout
    timeoutActive = window.setTimeout(function() { // sets the new timeout and saves the status in the global variable timeoutActive
        display();
    }, 15000);
}