使用jQuery .promise()來調用clearInterval()

[英]using jQuery .promise() to call clearInterval()


I have been experimenting a lot with setInterval and clearInterval recently, for creating my own custom effects and one of the things that I have been working on is an efficient way to clear an interval whilst staying out of the global scope. I am trying to improve readability and explore possible performance boosts by using .promise() to call clearInterval() (the below is an example of what I'm trying to do):

我最近用setInterval和clearInterval進行了大量的實驗,用於創建我自己的自定義效果,我一直在研究的一個方法是在遠離全局范圍時清除間隔的有效方法。我試圖通過使用.promise()來調用clearInterval()來提高可讀性並探索可能的性能提升(下面是我正在嘗試做的一個例子):

//caller is a collection of elements
function performEffect(caller) {
   var interval = setInterval(function() { caller.next(); }, 500);
   caller.promise().done(function() { interval = clearInterval(interval); });
}

Up until recently, I had been setting and clearing the interval using an embedded function (example):

直到最近,我一直使用嵌入式功能設置和清除間隔(示例):

function performEffect(caller) {
   var interval;
   var count = 0;
   var len = caller.length;

   if (count >= len) {
       interval = clearInterval(interval);
   }

   var tmr = function () {
       interval = setInterval(function () { effectFunciton(count++); }, 100);
   }
}

P.S. I'm sorry for not posting the original - my versioning system was corrupted. Also, I know that this example is kind of silly, since I could easily use a for-loop or a .each(), but it's just an example - I do have instances where I do not want to use a loop.

附:對不發布原文我很抱歉 - 我的版本控制系統已損壞。另外,我知道這個例子有點傻,因為我可以很容易地使用for循環或.each(),但它只是一個例子 - 我確實有我不想使用循環的實例。

This is my first post, so I apologize ahead of time if I do something different from the accepted practice. Please let me know if there is anything I can do to improve my posts in the future - I'm always open to constructive criticism :)

這是我的第一篇文章,所以如果我做的不同於公認的做法,我會提前道歉。如果有任何我可以做的事情來改善我的帖子,請告訴我 - 我總是接受建設性的批評:)

Thanks!

1 个解决方案

#1


5  

You'll want to use deferreds for this. I wrote an example on jsfiddle a little while ago that may give you some insight.

你會想要使用deferreds。我剛才在jsfiddle上寫了一個例子,可能會給你一些見解。

http://jsfiddle.net/landau/M3Lj4/

From your code, it looks like you are misunderstanding deferreds in general or there isn't enough code here to tell what you are doing. Promises hides resolving and rejecting functionality

從您的代碼中看,您似乎總是誤解延遲,或者這里沒有足夠的代碼來告訴您正在做什么。 Promise隱藏了解析和拒絕功能

Basically,

var deferred = $.Deferred();
var promise = deferred.promise();

// This will only run once
var timer = setInterval( function () {
    deferred.resolve();
}, 1000);

promise.done(function () {
    clearInterval( timer );
});

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/07/06/72515d92f99c06bb2f7d8209730c99fa.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com