从头开始强调延迟
underscore delay from scratch
我正在研究下划线延迟以提高我的 JS 技能,并且我正在尝试向自己解释每一行以确保我理解。有人可以解释这条线在做什么吗?
var args = Array.prototype.slice.call(arguments, 2);
它是否采用参数数组的前 2 个值并使其等于 var 'args'?
另外,
不应该"wait"是3000毫秒这样的数值吗?想知道为什么要拼写出来?
_.delay = function(func, wait) {
var args = Array.prototype.slice.call(arguments, 2);
setTimeout(function(){
func.apply(this, args);
}, wait);
};
var args = Array.prototype.slice.call(arguments, 2);
此行将传递给 _delay
的前 2 个参数以外的所有参数传递给 setTimeout
。
wait
被拼写出来是因为它是您要传递给 _.delay()
:
的参数
_.delay(function(){
// Do stuff
}, 1000)`;
此参数随后也传递给 setTimeout
基本上,_.delay
的实现 与 setTimeout
完全相同,缺点是它不 return可以用于 clear the timeout.
的超时标识符
var args = Array.prototype.slice.call(arguments, 2);
正在从第二个索引开始的数组中提取(返回)所有元素。在浏览器控制台试试这个:
Array.prototype.slice.call([1, 2, 3, 4, 5], 2)
// Output: [3, 4, 5]
关于wait
:由于wait
是传递的参数之一,所以拼写出来。 wait
的内容应该是一个整数(以毫秒为单位),因为这是 setTimeout(callback, timeInMilliseconds)
期望的第二个参数。
我正在研究下划线延迟以提高我的 JS 技能,并且我正在尝试向自己解释每一行以确保我理解。有人可以解释这条线在做什么吗?
var args = Array.prototype.slice.call(arguments, 2);
它是否采用参数数组的前 2 个值并使其等于 var 'args'?
另外,
不应该"wait"是3000毫秒这样的数值吗?想知道为什么要拼写出来?
_.delay = function(func, wait) {
var args = Array.prototype.slice.call(arguments, 2);
setTimeout(function(){
func.apply(this, args);
}, wait);
};
var args = Array.prototype.slice.call(arguments, 2);
此行将传递给 _delay
的前 2 个参数以外的所有参数传递给 setTimeout
。
wait
被拼写出来是因为它是您要传递给 _.delay()
:
_.delay(function(){
// Do stuff
}, 1000)`;
此参数随后也传递给 setTimeout
基本上,_.delay
的实现 与 setTimeout
完全相同,缺点是它不 return可以用于 clear the timeout.
var args = Array.prototype.slice.call(arguments, 2);
正在从第二个索引开始的数组中提取(返回)所有元素。在浏览器控制台试试这个:
Array.prototype.slice.call([1, 2, 3, 4, 5], 2)
// Output: [3, 4, 5]
关于wait
:由于wait
是传递的参数之一,所以拼写出来。 wait
的内容应该是一个整数(以毫秒为单位),因为这是 setTimeout(callback, timeInMilliseconds)
期望的第二个参数。