在JavaScript/jQuery中,要实现非阻塞睡眠,可以使用以下方法:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function nonBlockingSleep() {
console.log('Start sleeping...');
await sleep(3000); // 等待3秒
console.log('Finished sleeping!');
}
nonBlockingSleep();
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function nonBlockingSleep() {
console.log('Start sleeping...');
await sleep(3000); // 等待3秒
console.log('Finished sleeping!');
}
nonBlockingSleep();
function sleep(ms) {
var deferred = $.Deferred();
setTimeout(function() {
deferred.resolve();
}, ms);
return deferred.promise();
}
function nonBlockingSleep() {
console.log('Start sleeping...');
sleep(3000).then(function() { // 等待3秒
console.log('Finished sleeping!');
});
}
nonBlockingSleep();
这些方法都可以实现在JavaScript/jQuery中非阻塞地暂停代码执行一段时间。
领取专属 10元无门槛券
手把手带您无忧上云