MooTools - 定期執行



MooTools 提供了一個支援定期執行的功能。透過這個功能,它可以以相同的頻率週期性地呼叫一個函式。讓我們討論一下定期執行的方法和特性。

periodical()

此方法用於以相同的頻率週期性地執行一個函式。在開始之前,我們需要定義一些內容。一個是你要定期執行的函式,另一個是數值,表示你希望函式執行的頻率(以毫秒為單位的數值)。讓我們來看一個例子,解釋如何使函式每 100 毫秒執行一次。請看下面的程式碼。

示例

<!DOCTYPE html>
<html>

   <head>
      <script type = "text/javascript" src = "MooTools-Core-1.6.0.js"></script>
      <script type = "text/javascript" src = "MooTools-More-1.6.0.js"></script>
      
      <script type = "text/javascript">
         var periodicalFunction = function(){
            document. writeln("www.tutorialspoint.com");
         }
         
         window.addEvent('domready', function() {
            //number at the end indicates how often to fire, measure in milliseconds
            var periodicalFunctionVar = periodicalFunction.periodical(100);
         });
      </script>
   </head>
   
   <body>
   </body>
   
</html>

你將收到以下輸出:

輸出

元素作為第二個變數

periodical 函式還綁定了一個位於 domready 函式() 之外的第二個變數。你可以將元素作為第二個變數繫結到要定期執行的函式中。請看下面的語法,瞭解如何傳遞變數。

語法

window.addEvent('domready', function() {
   //pass something to a var
   var passedVar = $('elementID');
   
   //now periodicalFunction will be able to use "this" to refer to "passedVar"
   var periodicalFunctionVar = periodicalFunction.periodical(100, passedVar);
});

這裡,passedVar 是一個儲存 html 元素的元素變數。該變數作為第二個變數傳遞給 periodical 函式 periodicalFunctionVar

$clear()

此方法用於停止 periodical 函式。此方法有助於重置 periodical 變數的值。請看下面的語法,瞭解如何使用 $clear() 函式。

語法

//we clear the var that we passed the function and periodical to
$clear(periodicalFunctionVar);
廣告
© . All rights reserved.