user6651317
user6651317

Reputation:

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("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.

Upvotes: 2

Views: 44

Answers (1)

AndrewL64
AndrewL64

Reputation: 16331

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);

Upvotes: 1

Related Questions