Function

Module: @ember/runloop
target
Object
target of method to invoke
method
Function|String
The method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target.
args*
Object
Optional arguments to pass to the timeout.
wait
Number
Number of milliseconds to wait.
immediate
Boolean
Trigger the function on the leading instead of the trailing edge of the wait interval. Defaults to false.
returns
Array
Timer information for use in canceling, see `cancel`.

Delay calling the target method until the debounce period has elapsed with no additional debounce calls. If debounce is called again before the specified time has elapsed, the timer is reset and the entire period must pass again before the target method is called.

This method should be used when an event may be called multiple times but the action should only be called once when the event is done firing. A common example is for scroll events where you only want updates to happen once scrolling has ceased.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { debounce } from '@ember/runloop';

function whoRan() {
  console.log(this.name + ' ran.');
}

let myContext = { name: 'debounce' };

debounce(myContext, whoRan, 150);

// less than 150ms passes
debounce(myContext, whoRan, 150);

// 150ms passes
// whoRan is invoked with context myContext
// console logs 'debounce ran.' one time.

Immediate allows you to run the function immediately, but debounce other calls for this function until the wait time has elapsed. If debounce is called again before the specified time has elapsed, the timer is reset and the entire period must pass again before the method can be called again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { debounce } from '@ember/runloop';

function whoRan() {
  console.log(this.name + ' ran.');
}

let myContext = { name: 'debounce' };

debounce(myContext, whoRan, 150, true);

// console logs 'debounce ran.' one time immediately.
// 100ms passes
debounce(myContext, whoRan, 150, true);

// 150ms passes and nothing else is logged to the console and
// the debouncee is no longer being watched
debounce(myContext, whoRan, 150, true);

// console logs 'debounce ran.' one time immediately.
// 150ms passes and nothing else is logged to the console and
// the debouncee is no longer being watched