<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>waitFor函式</title>
</head>
<body>
<input type="button" id="b1" value="Start (5000ms)" />
<input type="button" id="b2" value="Start (1000ms)" />
<hr />
<input type="button" id="trg" value="Trigger" />
<hr />
<ul id="display"></ul>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
/**
* 條件成立時才執行
*
* @param check 檢查函式
* @param timeout 最長等待時間
* @param checkInterval 檢查間隔
*/
jQuery.waitFor = function(check, timeout, checkInterval) {
var dfd = jQuery.Deferred();
var checkHandle = setInterval(function () {
if (check()) {
clearInterval(checkHandle);
dfd.resolve();
}
}, checkInterval || 50);
var timeoutHandle = setTimeout(function () {
if (dfd.state() == "pending") {
clearInterval(checkHandle);
clearTimeout(timeoutHandle);
dfd.reject();
}
}, timeout || 5000);
return dfd.promise();
}
//測試程式
var $disp = $("#display");
function log(msg) {
var t = JSON.stringify(new Date()).split('T')[1].substr(0, 12);
$disp.append("<li>" + t + " " + msg + "</li>")
}
var state = false;
function init() {
state = false;
log("Start");
}
function trigger() {
state = true;
log("Trigger");
}
$("#b1").click(function() {
init();
$.waitFor(function() { return state; }, 5000)
.done(function() { log("Executed"); }).fail(function() { log("Timeout"); });
});
$("#b2").click(function() {
init();
$.waitFor(function() { return state; }, 1000)
.done(function() { log("Executed"); }).fail(function() { log("Timeout"); });
});
$("#trg").click(trigger);
</script>
</body>
</html>