1

setTimeout についてさまざまな質問がclearTimeout(content.idTimeout) あります。私は次のモデルを持っています:

var ContentModel = Backbone.Model.extend({
URL: "http://localhost/example.php",    
requestType: "POST",
dataType: "json",
data: "", //Set the value outside the model
idTimeout: "",  
initialize: function() {
_.bindAll(this);
},   
startSend: function (Data) { },
reply: function (Data) { 
    var dataJson = eval(Data);              
    console.log(dataJson);
    this.idTimeout = setTimeout(this.ajaxRequest(),4000);
},
problems: function (Data) {   },
ajaxRequest: function () {
    $.ajax({
        async:true,
        type: this.requestType,  dataType: this.dataType, 
        url: this.URL,  data: this.data,
        beforeSend:this.startSend,  success: this.reply,
        timeout:4000,  error:this.problems 
    });
}

そして、ビュー(フラグメント)のタイムアウトをきれいにします:

initialize: function() {
    _.bindAll(this); 
    this.model = new ContentCollection();
    this.model.on("add", this.contentAdded);
        this.model.on("remove", this.removeContent);    
},
contentAdded: function(content) { //run it when add a model
    if (content.view == null) {
    var template_name = 'cam';                                                      
    content.view = new ContentView({model: content,template: $.trim($("[template='"+ template_name +"'] div").html() || "Template not found!")});
    $("div.camBox").empty();                
    content.ajaxRequest();                              
    this.$el.find(".content").find("div.camBox").append(content.view.render().el);                                              
    }                   
},  
removeContent: function(content) {
    if (content.view != null) { 
        content.view.remove();              
    }
    clearTimeout(content.idTimeout);
    content.clear();  //Clear the properties of the model   
}

- フォーカスが他のウィンドウにあるときのタイムアウトをどのようにきれいにし、戻ったときにそれを再開しますか? おそらくフォーカス方式で。次のコード

$('html').focus(function() {
    clearTimeout(content.idTimeout);
});

contentAdded では機能しません。

編集:

http://stackoverflow.com/questions/14258596/way-to-stop-the-running-of-a-javascript-web-application-when-the-focus-is-on-oth

4

1 に答える 1

3

1つの解決策は次のとおりです。

(複数の) タイムアウト ID の配列を指定します。

window.timeouts = [];

setTimeout を呼び出すたびに:

timeouts.push(setTimeout(...));

次に、すべてのタイムアウトを停止する場合:

for(var i in timeouts) {
  clearTimeout(timeouts[i]);
}
于 2013-01-10T12:09:16.343 に答える