mirror of
				https://gitee.com/coder-xiaomo/leetcode-problemset
				synced 2025-11-04 19:53:12 +08:00 
			
		
		
		
	
		
			
				
	
	
		
			44 lines
		
	
	
		
			1.9 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
			
		
		
	
	
			44 lines
		
	
	
		
			1.9 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
<p>Given a function <code>fn</code>, an array or arguments <code>args</code>, and a timeout <code>t</code> in milliseconds, return a cancel function <code>cancelFn</code>.</p>
 | 
						|
 | 
						|
<p>After a delay of <code>t</code>, <code>fn</code> should be called with <code>args</code> passed as parameters <strong>unless</strong> <code>cancelFn</code> was called first. In that case, <code>fn</code> should never be called.</p>
 | 
						|
 | 
						|
<p> </p>
 | 
						|
<p><strong class="example">Example 1:</strong></p>
 | 
						|
 | 
						|
<pre>
 | 
						|
<strong>Input:</strong> fn = (x) => x * 5, args = [2], t = 20, cancelTime = 50
 | 
						|
<strong>Output:</strong> [{"time": 20, "returned": 10}]
 | 
						|
<strong>Explanation:</strong> 
 | 
						|
const cancel = cancellable(fn, [2], 20); // fn(2) called at t=20ms
 | 
						|
setTimeout(cancel, 50);
 | 
						|
 | 
						|
the cancelTime (50ms) is after the delay time (20ms), so fn(2) should be called at t=20ms. The value returned from fn is 10.
 | 
						|
</pre>
 | 
						|
 | 
						|
<p><strong class="example">Example 2:</strong></p>
 | 
						|
 | 
						|
<pre>
 | 
						|
<strong>Input:</strong> fn = (x) => x**2, args = [2], t = 100, cancelTime = 50
 | 
						|
<strong>Output:</strong> []
 | 
						|
<strong>Explanation:</strong> fn(2) was never called because cancelTime (50ms) is before the delay time (100ms).
 | 
						|
</pre>
 | 
						|
 | 
						|
<p><strong class="example">Example 3:</strong></p>
 | 
						|
 | 
						|
<pre>
 | 
						|
<strong>Input:</strong> fn = (x1, x2) => x1 * x2, args = [2,4], t = 30, cancelTime = 100
 | 
						|
<strong>Output:</strong> [{"time": 30, "returned": 8}]
 | 
						|
<strong>Explanation:</strong> fn(2, 4) was called at t=30ms because cancelTime > t.
 | 
						|
</pre>
 | 
						|
 | 
						|
<p> </p>
 | 
						|
<p><strong>Constraints:</strong></p>
 | 
						|
 | 
						|
<ul>
 | 
						|
	<li><code>fn is a function</code></li>
 | 
						|
	<li><code>args is a valid JSON array</code></li>
 | 
						|
	<li><code>1 <= args.length <= 10</code></li>
 | 
						|
	<li><code><font face="monospace">20 <= t <= 1000</font></code></li>
 | 
						|
	<li><code><font face="monospace">10 <= cancelT <= 1000</font></code></li>
 | 
						|
</ul>
 |