gpt4 book ai didi

javascript - 如何仅当用户在页面上停留超过一秒时检索数据

转载 作者:行者123 更新时间:2023-11-28 15:38:27 25 4
gpt4 key购买 nike

在 AngularJS 应用程序中,用户可以浏览多个页面。每次显示页面时, Controller 都会向服务器获取一些数据。

我想在启动请求之前等待 1 秒,因此如果用户快速离开页面前往另一个 View ,我们不会加载数据。

我尝试使用 $timeout,但即使已加载其他 View 和其他 Controller ,查询也会执行。

app.controller('showController', function($scope, $routeParams, $timeout){
$timeout(function(){
Service.getDataDetails(id).then(function (result) {
$scope.data = result;
});
},1000);
});

我还尝试取消查询。查询在导航器中被很好地取消,但服务器仍然执行它。

最佳答案

在 Controller 的析构函数中取消您的$timeout:

$scope.$on("$destroy", function handler() {
$timeout.cancel(promise);
});

当不再使用 Controller 时调用它。

<小时/>

Patrick Evens 提醒我告诉你 Promise 变量来自哪里:

var promise = $timeout(function(){
Service.getDataDetails(id).then(function (result) {
$scope.data = result;
});
},1000);

关于javascript - 如何仅当用户在页面上停留超过一秒时检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24827649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com