When writing an Angularjs project, you need to write a fuzzy query requirement. Because you need to control the query frequency, you add a timer setTimeOut(FN,500) to the query event. This timer is used to trigger the query every 0.5 seconds to reduce background stress. But later found that did not have the desired effect, and finally found the timer is carried out, no clear in time, because extra timer timer stack implementation, although the delay time of 0.5 seconds play a role, but in this delay time, the front of the timer function in the implementation, finally caused the appearance of similar didn’t work, In fact, it is the result of each timer running out after 0.5 seconds.
$scope.orgTable = [];
$scope.timerBill = null;
$scope.fuzzyQuery = function () {
$scope.orgArr = [];
var value = $('#orgChecked').val();
if($scope.timerBill){
clearTimeout($scope.timerBill);
}
if (value.length) {
$scope.timerBill=setTimeout(function () {
$http.get(Configuration.latestAPI + 'xxx? sso_token=' + Configuration.token).success(function (res) {
if (res.status == 'S') {}})}, 300); }else{}};Copy the code
The following part of the code is added to the code, which is mainly to clear the timer left by the previous execution each time the fuzzy query function starts, so as to ensure that there is only one timer running forever.
if($scope.timerBill){
clearTimeout($scope.timerBill);
}
Copy the code
Conclusion: if the timer is used in the function with frequent triggering times, it must be remembered at the beginning of the function to clear the possible remaining timer, and ensure that only one timer exists in the whole function execution process to ensure the correct execution of the function.