| [ Index ] |
PHP Cross Reference of Moodle 310 |
[Summary view] [Print] [Text view]
1 // This file is part of Moodle - http://moodle.org/ 2 // 3 // Moodle is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU General Public License as published by 5 // the Free Software Foundation, either version 3 of the License, or 6 // (at your option) any later version. 7 // 8 // Moodle is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU General Public License for more details. 12 // 13 // You should have received a copy of the GNU General Public License 14 // along with Moodle. If not, see <http://www.gnu.org/licenses/>. 15 16 /** 17 * Utility functions. 18 * 19 * @module core/utils 20 * @copyright 2019 Ryan Wyllie <ryan@moodle.com> 21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 22 */ 23 24 /** 25 * Create a wrapper function to throttle the execution of the given 26 * 27 * function to at most once every specified period. 28 * 29 * If the function is attempted to be executed while it's in cooldown 30 * (during the wait period) then it'll immediately execute again as 31 * soon as the cooldown is over. 32 * 33 * @method 34 * @param {Function} func The function to throttle 35 * @param {Number} wait The number of milliseconds to wait between executions 36 * @return {Function} 37 */ 38 export const throttle = (func, wait) => { 39 let onCooldown = false; 40 let runAgain = null; 41 const run = function(...args) { 42 if (runAgain === null) { 43 // This is the first time the function has been called. 44 runAgain = false; 45 } else { 46 // This function has been called a second time during the wait period 47 // so re-run it once the wait period is over. 48 runAgain = true; 49 } 50 51 if (onCooldown) { 52 // Function has already run for this wait period. 53 return; 54 } 55 56 func.apply(this, args); 57 onCooldown = true; 58 59 setTimeout(() => { 60 const recurse = runAgain; 61 onCooldown = false; 62 runAgain = null; 63 64 if (recurse) { 65 run(args); 66 } 67 }, wait); 68 }; 69 70 return run; 71 }; 72 73 /** 74 * Create a wrapper function to debounce the execution of the given 75 * function. Each attempt to execute the function will reset the cooldown 76 * period. 77 * 78 * @method 79 * @param {Function} func The function to debounce 80 * @param {Number} wait The number of milliseconds to wait after the final attempt to execute 81 * @return {Function} 82 */ 83 export const debounce = (func, wait) => { 84 let timeout = null; 85 return function(...args) { 86 clearTimeout(timeout); 87 timeout = setTimeout(() => { 88 func.apply(this, args); 89 }, wait); 90 }; 91 };
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated: Wed Jan 22 11:59:49 2025 | Cross-referenced by PHPXref 0.7.1 |