Passing Custom Parameters to setTimeout Callback

Use-Cases of this Tutorial

  • Pass custom parameters to setTimeout() callback function.

Developers generally pass only two parameters to setTimeout method — the callback function and the timeout period. But in many cases we need to pass custom dynamic data to the callback.

This can be easily done by knowing that the setTimeout method can have multiple parameters depending on our need. We can pass custom parameters after the callback function and timeout parameters. These custom parameters are passed to the callback function — as its parameters.

setTimeout(function(param_1, param_2, param_3) {
	// "One"
	console.log(param_1);

	// "Two"
	console.log(param_2);

	// "Three"
	console.log(param_3);
}, 2000, "One", "Two", "Three");
setTimeout(customFunction, 2000, 12202, "Test Name", "SAMPLE", "This is a test");

// custom parameters to setTimeout are passed are parameters to the callback
function customFunction(id, name, type, description) {
	// 12202
	console.log(id);

	// "Test Name"
	console.log(name);

	// "SAMPLE"
	console.log(type);

	// "This is a test"
	console.log(description);
}

Note that we can pass any number of custom parameters with this.