[英]Chaining methods with delays in javascript
I'm attempting to make this piece of code more efficient. 我试图使这段代码更高效。
(function() {
sc = angular.element('tbody').scope(); sc.draft.resetRoster(); sc.$apply();
setTimeout(function() {
sc.draft.rosterAdd({id: "12921", salary: 10600, position: "P"});sc.draft.rosterAdd({id: "12123", salary: 2900, position: "C"});sc.draft.rosterAdd({id: "5435", salary: 3800, position: "1B"});sc.draft.rosterAdd({id: "12562", salary: 2400, position: "2B"});sc.draft.rosterAdd({id: "38321", salary: 3100, position: "3B"});sc.draft.rosterAdd({id: "6319", salary: 2400, position: "SS"});sc.draft.rosterAdd({id: "5204", salary: 3200, position: "OF"});sc.draft.rosterAdd({id: "5222", salary: 2500, position: "OF"});sc.draft.rosterAdd({id: "12462", salary: 2600, position: "OF"});
}, 3000);
setTimeout(function() {
document.querySelector('#enterButton').click();
}, 6000);
})();
I'm not entirely familiar with Angular (actually not at all). 我对Angular并不完全熟悉(实际上一点都不熟悉)。 I'm trying to create a client-side script that interacts with Angular. 我正在尝试创建一个与Angular交互的客户端脚本。 There's 5 total statements here that I'm trying to condense into as little code as possible. 这里有5条语句,我试图将它们压缩为尽可能少的代码。 Before the first setTimeout
gets triggered in 3,000ms, I need this to run: sc = angular.element('tbody').scope(); sc.draft.resetRoster(); sc.$apply();
在第一个setTimeout
在3,000毫秒内触发之前,我需要运行此命令: sc = angular.element('tbody').scope(); sc.draft.resetRoster(); sc.$apply();
sc = angular.element('tbody').scope(); sc.draft.resetRoster(); sc.$apply();
After 3,000ms, the first setTimeout
runs. 3,000毫秒后,第一个setTimeout
运行。 Roughly 6,000ms (assuming there's roughly a ~3,000ms gap between the first setTimeout
and second setTimeout
) I need the second setTimeout
to execute. 大约6,000ms(假设第一个setTimeout
和第二个setTimeout
之间大约有3,000ms的差距),我需要第二个setTimeout
才能执行。
Is there a better way to put together this function? 有没有更好的方法来组合此功能? Less code? 更少的代码? Better sequencing of how I'm handling setTimeout
in general? 通常如何更好地排序setTimeout
顺序?
Instead of setTimeout
use angular service $timeout
which functions similarly but returns a promise
that will be resolved after the specified amount of time has elapsed, and also calls $apply
. 代替setTimeout
使用角度服务$timeout
,它的功能类似,但是返回一个promise
,该promise
将在经过指定的时间后解决,并调用$apply
。 So in your case: 因此,在您的情况下:
$timeout(function () { ... }, 3000).then(function () {
//after the first timeout we set another one and return its promise
$timeout(function () { ... }, 3000);
});
This way you get rid off the mental arithmetic and you can just set the time you want to wait after the last timeout has elapsed, without nesting timeout functions. 这样,您就可以摆脱思维算术,并且可以设置上一次超时后要等待的时间,而无需嵌套超时功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.