I have a interval set up like this:

var inte = setInterval(function(){
        clearInterval(inte);
    },1000);

Is there a way that i can do it like this?

setInterval(function(){
        clearInterval(this);
    },1000);
有帮助吗?

解决方案

I think you'd need to wrap setInterval in your own mySetInterval that keeps track of the clearable id:

function mySetInterval(f,t) {
  var x =
    setInterval(
      function() {
        f();
        clearInterval(x);
      },
      t 
    )
}

mySetInterval(function() { alert("foo"); }, 1000);

其他提示

Since you seem to be running this only once, why not use setTimeout instead?

setTimeout(function(){
   // do your stuff here
}, 1000);

No need to clear anything in this case.

Store the function inside a variable. Then you can use the native .apply() function to apply arguments and set the functions 'this' variable. Google should know some examples on .apply(), but why don't you use setTimeout(function(){},1000)? Then you wouldn't need to clear an interval because this only gets executed once.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top