How to implement a “function timeout” in Javascript - not just the 'setTimeout'

后端 未结 5 1370
情歌与酒
情歌与酒 2020-12-16 00:33

How to implement a timeout in Javascript, not the window.timeout but something like session timeout or socket timeout - basically - a

5条回答
  •  眼角桃花
    2020-12-16 00:39

    You can achieve this only using some hardcore tricks. Like for example if you know what kind of variable your function returns (note that EVERY js function returns something, default is undefined) you can try something like this: define variable

    var x = null;
    

    and run test in seperate "thread":

    function test(){
        if (x || x == undefined)
            console.log("Cool, my function finished the job!");
        else
            console.log("Ehh, still far from finishing!");
    }
    setTimeout(test, 10000);
    

    and finally run function:

    x = myFunction(myArguments);
    

    This only works if you know that your function either does not return any value (i.e. the returned value is undefined) or the value it returns is always "not false", i.e. is not converted to false statement (like 0, null, etc).

提交回复
热议问题