Một đóng cửa dựa trên giải pháp, sử dụng.210 và clearInterval()
:
// define a generic repeater
var repeater = function(func, times, interval) {
var ID = window.setInterval(function(times) {
return function() {
if (--times <= 0) window.clearInterval(ID);
func();
}
}(times), interval);
};
// call the repeater with a function as the argument
repeater(function() {
alert("stuff happens!");
}, 3, 60000);
EDIT: Một cách khác để thể hiện giống nhau, sử dụng setTimeout()
thay vì:
var repeater = function(func, times, interval) {
window.setTimeout(function(times) {
return function() {
if (--times > 0) window.setTimeout(arguments.callee, interval);
func();
}
}(times), interval);
};
repeater(function() {
alert("stuff happens!");
}, 3, 2000);
Có lẽ sau này là một chút dễ hiểu hơn.
Trong phiên bản setTimeout()
bạn có thể đảm bảo rằng lần lặp tiếp theo chỉ xảy ra sau trước đó đã kết thúc chạy. Bạn chỉ cần di chuyển số func()
dòng lên trên đường dây setTimeout()
.
nhanh chóng và dơ bẩn, nhưng tại sao không chỉ tăng số lượt truy cập mỗi khi yêu cầu được chạy và nếu (counter <3) {intervalRun();}? – Optimate
@optimate: intervalRun() là gì? – Nosredna
Anh ấy muốn nói 'setInterval'. – SLaks