我已经实现了一个函数,而数组推送操作符则执行某些操作。
如下所示:当推送数据时,它将调用refreshView一次; 但是当循环100次按下操作时,它将调用refreshView 100次;
任何想法在完成循环时调用最后一个refreshView()
var arr = [];
arr.push = function () {
Array.prototype.push.apply(this, arguments);
refreshView();
}
function refreshView() {
// perform some operations
}
arr.push(1); // it will call refreshView() 1 times;
for (var i = 0; i < 100; i++) {
arr.push(i); // it will call refreshView() 100 times, how can i call refreshView() once after loop finish..
}
答案 0 :(得分:0)
最佳选择是使用超时来延迟函数调用,因此只应在完成时运行:
var arr = [];
var timer;
arr.push = function () {
Array.prototype.push.apply(this, arguments);
if(timer)
{
clearTimeout(timer);
)
timer = setTimeout(refreshView, 10);
}
function refreshView() {
// perform some operations
}
arr.push(1); // it will call refreshView() 1 times;
for (var i = 0; i < 100; i++) {
arr.push(i); // it will call refreshView() 100 times, how can i call refreshView() once after loop finish..
}