當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


underscore.js _.after()用法及代碼示例

Underscore.js是一個JavaScript庫,它提供了許多有用的函數,即使不使用任何內置對象,它們也可以以很大的方式幫助編程,例如映射,過濾器,調用等。

_.after()函數是JavaScript的Underscore.js庫中的內置函數,用於創建函數的包裝,該包裝一開始不執行任何操作,但從指定的計數開始,它將調用指定的函數。此外,它在異步響應分組中很有用,因為您需要確定所有異步調用在結束之前是否已經結束。

用法:

_.after(count, function)

參數:它接受以下指定的兩個參數:

  • count:它是計數的數量,之後將調用所述函數。
  • function:它是規定的函數。

返回值:此方法返回調用函數的計數。



範例1:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> 
    </script> 
</head> 
  
<body> 
    <script> 
        show = () => { 
            console.log("GeeksforGeeks") 
        } 
        console.log(`Show function will run for 5 times:`) 
  
        // Calling after function 
        func = _.after(3, show); 
        func(); 
        func(); 
        func(); 
        func(); 
        func(); 
        func(); 
        func();  
    </script> 
</body> 
  
</html>

輸出:

Show function will run for 5 times:
 GeeksforGeeks
 GeeksforGeeks
 GeeksforGeeks
 GeeksforGeeks
 GeeksforGeeks

範例2:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> 
    </script> 
</head> 
  
<body> 
    <button id="button">button</button> 
    <script> 
        show = () => { 
            console.log("GeeksforGeeks") 
        } 
  
        // Calling after function 
        func = _.after(3, show); 
        let button = document.querySelector("#button"); 
        let Run = () => { 
            console.log(`Show function runs for 8 times:`) 
            for (let i = 0; i < 10; i++) { 
                func(); 
            } 
        } 
        button.addEventListener("click", Run)   
    </script> 
</body> 
  
</html>

輸出:

button

Show function runs for 7 times:
 GeeksforGeeks
 GeeksforGeeks
 GeeksforGeeks
 GeeksforGeeks
 GeeksforGeeks
 GeeksforGeeks
 GeeksforGeeks
 GeeksforGeeks

在這裏,您需要單擊按鈕以查看輸出。

參考:https://underscorejs.org/#after




相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Underscore.js _.after() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。