gpt4 book ai didi

javascript - 是否可以从内部 Promise 获取父函数的回调?

转载 作者:行者123 更新时间:2023-12-02 15:05:57 24 4
gpt4 key购买 nike

Play with my JSfiddle

是否可以使用 $timeout promise 使 scrollTo 可链接,如下所示?如果没有,我如何编写scrollTo作为 promise ,以便我可以使用then回调?

html:

<div ng-click=toTop()>click me</div>

js:

app.controller('MainCtrl', function($scope, $timeout) {
$scope.toTop = function() {
var bodyEl = angular.element(document.querySelector('#body'));
scrollTo_(bodyEl[0], 0, 500);

};


function scrollTo_(element, to, duration) {
if (duration <= 0) {
$timeout.cancel(forward);
console.log('yoyo');
return forward;
}
var difference = to - element.scrollTop;
var perTick = difference / duration * 10;
var forward = $timeout(function() {
element.scrollTop = element.scrollTop + perTick;
scrollTo_(element, to, duration - 10);
}, 10, false);
}
});

最佳答案

这就是我完成递归 promise 的方式:

function scrollTo_(element, to, duration) {
if(duration<=0) return Promise.resolve();
var difference = to - element.scrollTop,
perTick = difference / duration * 10;
return $timeout(function() {
element.scrollTop = element.scrollTop + perTick;
}, 10, false).then(function(){
duration -= 10;
return scrollTo_(element, to, duration)
});
}

编辑:

如果你想停止中间的超时,我想你可以这样做:

var scrollTopTimeoutFlag = true, scrollTopTimeout;
function scrollTo_(element, to, duration) {
if(duration<=0 || !scrollTopTimeoutFlag){
if(scrollTopTimeout) return $timeout.cancel(scrollTopTimeout);
return $q.when(); // $q.when == Promise.resolve
}
var difference = to - element.scrollTop,
perTick = difference / duration * 10;
scrollTopTimeout = $timeout(function() {
element.scrollTop = element.scrollTop + perTick;
}, 10, false);
return scrollTopTimeout.then(function(){
duration -= 10;
return scrollTo_(element, to, duration)
});
}

关于javascript - 是否可以从内部 Promise 获取父函数的回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35122368/

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