睡在JavaScript?

时间:2012-04-20 12:50:28

标签: javascript jquery

  

可能重复:
  Sleep in Javascript

我想在JavaScript中创建 sleep 函数,我必须在用户执行操作之前停止任何代码执行(如alert()行为)

我需要的是:我应该在此处插入什么才能使其正常工作?

window.alert = function(message){
    var dialog = $('<div>'+message+'</div>').dialog({
        title:'Alert',

        buttons:{
            'Ok': function(){
                $(this).dialog('close').data('open', false);
                $(this).remove();
            }
        }
    }).data('open', true);
    //What to insert here?
}

3 个答案:

答案 0 :(得分:2)

jQuery deferreds是最好的方法。它提供了一个很好的回调框架,因此更容易维护回调。

我创建了一个新功能,因为某些浏览器可能不允许您重新定义alert

myAlert = function(message){
var dfd = new $.Deferred();

var dialog = $('<div>'+message+'</div>').dialog({
    title:'Alert',

    buttons:{
        'Ok': function(){
            $(this).dialog('close').data('open', false);
            $(this).remove();
            dfd.resolve();
        }
    }
}).data('open', true);
return dfd.promise();
}

然后

myAlert(message).done(function() { callback here });

如果你想要你所评论的内容,就会这样。

myAlert(1).done(function() { myAlert(2) });

答案 1 :(得分:1)

你应该在这里使用回调,因为如果你停用javascript,用户将无法点击'确定'

window.alert = function(message, callback){
    var dialog = $('<div>'+message+'</div>').dialog({
        title:'Alert',

        buttons:{
            'Ok': function(){
                $(this).dialog('close').data('open', false);
                $(this).remove();
                typeof callback=='function' && callback(); //check if callback, and execute it
            }
        }
    }).data('open', true);
}
alert('test',function(){console.log('The user has clicked on the ok');});

修改

如果你只想暂停alert执行而不是其他代码执行你可以做这样的事情(我没有尝试过,但想法就在这里):

var alertStack=[];
window.alert = function(message){
  if(!message || !alertStack.length)
    $('<div>'+(alertStack[0] || message)+'</div>').dialog({
      title:'Alert',

      buttons:{
        'Ok': function(){
          alertStack.shift()
          $(this).dialog('close').data('open', false);
          $(this).remove();
          alertStack.length && alert();
        }
      }
    }).data('open', true);

  message && alertStack.push(message);
}
alert('test');
alert('test2');
alert('test3');

答案 2 :(得分:0)

如果要延迟执行代码但不希望重复执行代码,请使用setTimeout()。