Run JavaScript function on page load as well as on setInterval

问题: My current script setInterval(function() { $.ajax({ url:"query.php?currency=<?=$currencycode;?>" }).done(function(data) { $("#value").attr("...

问题:

My current script

setInterval(function() {
    $.ajax({
        url:"query.php?currency=<?=$currencycode;?>"
    }).done(function(data) {
        $("#value").attr("value", data).attr("size", data.length - 2);
    });
},3000);

My webpage is only query the php file every 3 seconds but I want to make it query when the page is open and then to execute the loop refreshing the value for my input every 3 seconds. Now you have to wait 3 seconds untill the value is updated.


回答1:

Separate the function from the setInterval() method and change the anonymous function to a named function.

Now all you have to do is invoke the function on page load as well as in setInterval() by just referencing the function name like this:

function someFunc() {
    $.ajax({
        url:"query.php?currency=<?=$currencycode;?>"
    }).done(function(data) {
        $("#value").attr("value", data).attr("size", data.length - 2);
    });
}

someFunc(); // function will invoke on page load

setInterval(someFunc, 3000); // function will invoke after every 3 seconds

Check and run the Code Snippet below for a practical example of the above approach:

function someFunc() {
  console.log("yes")
}

someFunc();
setInterval(someFunc, 3000);

  • 发表于 2019-01-21 05:09
  • 阅读 ( 227 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除