function printTime() {
console.log('It is time!');
}
setTimeout(printTime, 1000);
console.log('done');
會(huì)先打印done,1秒后才會(huì)打印It is time!
無(wú)效
'use strict';
function printTime() {
throw new Error();
}
try {
setTimeout(printTime, 1000);
console.log('done');
} catch (e) {
alert('error');
}
原因就在于調(diào)用setTimeout()函數(shù)時(shí)炸枣,傳入的printTime函數(shù)并未立刻執(zhí)行摄闸!緊接著禁漓,JavaScript引擎會(huì)繼續(xù)執(zhí)行console.log('done');語(yǔ)句赢乓,而此時(shí)并沒有錯(cuò)誤發(fā)生忧侧。直到1秒鐘后,執(zhí)行printTime函數(shù)時(shí)才發(fā)生錯(cuò)誤牌芋,但此時(shí)除了在printTime函數(shù)內(nèi)部捕獲錯(cuò)誤外蚓炬,外層代碼并無(wú)法捕獲。
<form>
<input id="x"> + <input id="y">
<button id="calc" type="button">計(jì)算</button>
</form>
'use strict';
var $btn = $('#calc');
// 取消已綁定的事件:
$btn.off('click');
無(wú)效
try {
$btn.click(function () {
var
x = parseFloat($('#x').val()),
y = parseFloat($('#y').val()),
r;
if (isNaN(x) || isNaN(y)) {
throw new Error('輸入有誤');
}
r = x + y;
alert('計(jì)算結(jié)果:' + r);
});
} catch (e) {
alert('輸入有誤躺屁!');
}
修改
$btn.click(function () {
try {
var
x = parseFloat($('#x').val()),
y = parseFloat($('#y').val()),
r;
if (isNaN(x) || isNaN(y)) {
throw new Error('輸入有誤');
}
r = x + y;
alert('計(jì)算結(jié)果:' + r);
}
catch (e) {
alert('輸入有誤肯夏!');
}
}
);