【问题标题】:setTimeout javascript not working properly [duplicate]setTimeout javascript无法正常工作[重复]
【发布时间】:2016-10-24 03:21:11
【问题描述】:

我想知道如何等待两次 5 秒,并在每次等待中使用 phantomjs 执行不同的操作。代码如下:

var page = require('webpage').create();

page.open("http://www.google.com/", function(status){

    var currentdate = new Date(); 

    console.log("\n\n" + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds() + "\n\n");


    setTimeout(function(){
        var currentdate1 = new Date(); 
        console.log("\n\n" + currentdate1.getHours() + ":" + currentdate1.getMinutes() + ":" + currentdate1.getSeconds() + "\n\n");
        return "hahaha";
    }, 5000);


    setTimeout(function(){
        var currentdate2 = new Date(); 
        console.log("\n\n" + currentdate2.getHours() + ":" + currentdate2.getMinutes() + ":" + currentdate2.getSeconds() + "\n\n");
        phantom.exit();
        return "hahaha";
    }, 5000);

});

为什么phantomjs第二个setTimeout函数不能正常工作??我怎么解决这个问题? 我想要实现的输出是这样的:

16:13:10
16:13:15
16:13:20

不是这个(就像现在这样):

16:13:10
16:13:15
16:13:15

对不起,我的英语不好。谢谢

【问题讨论】:

  • 两个超时现在开始,并等待五秒钟。您可以将一个嵌套在另一个中,或者将第二个设置为 10 秒。
  • 在开始第二个计时器之前重置第一个计时器:stackoverflow.com/a/315133/6908226
  • 您为什么要删除您的previous question 并创建一个新帐户?

标签: javascript phantomjs settimeout


【解决方案1】:

setTimeout 是异步的,当您启动一个时,代码不会停止运行,它会继续运行其他部分,您从那里启动第二个 setTimeout。要解决您的问题,您需要将第二个超时的延迟更改为10000,或者您需要在第一个超时内启动第二个超时。

【讨论】:

    猜你喜欢
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多