setTimeout
allows to run a function once after the interval of time.
- A call to
setTimeout
returns the timerId that we can use to cancel the execution.
function sayHi(phrase, who) {
alert( phrase + ', ' + who );
}
let timerId1 = setTimeout(sayHi, 1000, "Hello", "John"); // Hello, John
let timerId2 = setTimeout(() => alert('Hello'), 1000);
clearTimeout(timerId1);
clearTimeout(timerId2);
setInterval
allows running a function regularly with the interval between the runs.
// repeat with the interval of 2 seconds
let timerId = setInterval(() => alert('tick'), 2000);
// after 5 seconds stop
setTimeout(() => {
clearInterval(timerId);
alert('stop');
}, 5000);
- In browsers IE and Firefox the internal timer continues “ticking” while showing alert/confirm/prompt, but in Chrome, Opera and Safari the internal timer becomes “frozen”.
- For
setInterval
the function stays in memory until clearInterval
is called.
- There’s a side-effect that a function references the outer lexical environment, so, while it lives, outer variables live too.
- They may take much more memory than the function itself.
- So when we don’t need the scheduled function anymore, it’s better to cancel it, even if it’s very small.
Recursive setTimeout
- There are two ways of running something regularly, one is
setInterval
and the other one is a recursive setTimeout
.
let delay = 5000;
let serverRequest = () => {
// Send request...
if (requestFailed) {
setTimeout(serverRequest, delay);
}
}
- The recursive setTimeout is a more flexible method than setInterval.
- This way the next call may be scheduled differently, depending on the results of the current one.
- Recursive
setTimeout
guarantees a delay between the executions, setInterval
does not.
- When a function is passed in
setInterval
/setTimeout
, an internal reference is created to it and saved in the scheduler.
- It prevents the function from being garbage collected, even if there are no other references to it.
setTimeout(…,0)
- There’s a special use case:
setTimeout(func, 0)
.
- This schedules the execution of
func
as soon as possible.
- But scheduler will invoke it only after the current code is complete.
- So the function is scheduled to run “right after” the current code.
- In other words, asynchronously.
Debouncing
- Debouncing is a method of preventing a function from being invoked too often, and instead waiting a certain amount of time until it was last called before invoking it.
const inputEle = document.getElementById("inputElement");
const username = document.getElementById("username");
const generateUsername = (e) => username.innerHTML = e.target.value.split(" ").join("-");
const debounce = (callback, delay) => {
let timer;
return function () {
const context = this;
timer && clearTimeout(timer);
timer = setTimeout(() => callback.apply(context, arguments), delay);
}
}
inputEle.addEventListener("keyup", debounce(generateUsername, 300));